How to append text to an existing file in Java?
UPDATED: 29 June 2015
Tags:
BufferedWriter
,
FileWriter
,
io
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
public class AppendFileExample {
public static void main(String[] args) {
/* Content to write in File. */
String strFileData = "This excerpt demonstrate how you can append content in existing File using Java.";
/* Create object of File. */
File objFile = new File("D:\\Readme.txt");
try {
/* Check if File exists at given location. */
if (objFile.exists()) {
/**
* Constructs a FileWriter object given a file name with a boolean indicating whether or not to append the data
* - fileName String The system-dependent filename.
* - append boolean if true, then data will be written to the end of the file rather than the beginning.
*/
FileWriter objFileWriter = new FileWriter(objFile.getAbsolutePath(), true);
/* Create object of BufferedWriter. */
BufferedWriter objBufferedWriter = new BufferedWriter(objFileWriter);
/* Write content to File. */
objBufferedWriter.write(strFileData);
/* Close the BufferedWriter */
objBufferedWriter.close();
System.out.println("File modified!");
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
Other References:
How to write file in Java?
How to read file in Java?
How to read/parse XML file in Java?
Tags:
BufferedWriter
,
FileWriter
,
io
0 comments :