Append Text Existing File Java
In this below sample program you will see how to append text to an existing file using Java. There are many ways you can use to append text to an existing file here you will see using JDK 7 and older version of JDK:
- Sample java program:
package com.javahonk; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; public class AppendTextFile { public static void main(String[] args) { File file = new File("C:\\JavaHonk\\File\\AppendTextFile.txt"); if (file.exists()) try { file.createNewFile(); } catch (IOException e) { e.printStackTrace(); } //Using JDK 7 try (PrintWriter out = new PrintWriter(new BufferedWriter( new FileWriter("C:\\JavaHonk\\File\\AppendTextFile.txt", true)))) { out.println("Append this text to file"); } catch (IOException ioException) { ioException.printStackTrace(); } //Using java old versions: try { PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("C:\\JavaHonk\\File\\AppendTextFile.txt", true))); out.println("Append this text to file using java old version"); out.close(); } catch (IOException ioException) { ioException.printStackTrace(); } System.out.println("Text added successfully to the file: "+file.getAbsolutePath()); } }
- Output:
For information on Writing and Reading file please visit oracle site here