File Append In Java Example
Chapter:
File
Last Updated:
13-06-2016 19:28:30 UTC
Program:
/* ............... START ............... */
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
public class JavaFileAppendString {
public static void main(String[] args) {
try {
String content = " content will append to file";
File file = new File("JavaScan.txt");
// if file doesnt exists, then create it
if (!file.exists()) {
file.createNewFile();
}
// true = append file
FileWriter fileWritter = new FileWriter(file.getName(), true);
BufferedWriter bufferWritter = new BufferedWriter(fileWritter);
bufferWritter.write(content);
bufferWritter.close();
System.out.println("Done");
} catch (IOException e) {
e.printStackTrace();
}
}
}
/* ............... END ............... */
Output
The content "content will append to file" will add to the file.
Notes:
-
In order to append a file we needFileWriter instance with the append flag set to true.
- Syntax : BufferedWriter bw = new BufferedWriter(new FileWriter("file", true));
- FileWritter, a character stream to write characters to file. By default, it will replace all the existing content with new content.
Tags
File Creation, Java