Possible Duplicate: java append to file How to append data to a file?
I want to write a file in java without cleaning(deleting) older data
This is my try, but the current data will be cleaned on writing new data.
import java.io.*;
public class WriteToFileExample {
public static void main(String[] args) {
try {
String content = "New content to write to file";
File file = new File("/mypath/filename.txt");
// if file doesnt exists, then create it
if (!file.exists())
file.createNewFile();
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
bw.write(content);
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Use constructor FileWriter(String filename, boolean append)
that can instruct the file to be opened in append mode:
FileWriter fw = new FileWriter(file.getAbsoluteFile(), true);
//^^^^ means append
Try
FileWriter fw = new FileWriter(file, true);
Notes: second param means append; no need for file.getAbsoluteFile(), just File is OK
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With