I'm currently using FileWriter
to create and write to a file. Is there any way that I can write to the same file every time without deleting the contents in there?
fout = new FileWriter( "Distribution_" + Double.toString(_lowerBound) + "_" + Double.toString(_highBound) + ".txt"); fileout = new PrintWriter(fout,true); fileout.print(now.getTime().toString() + ", " + weight + ","+ count +"\n"); fileout.close();
From the Javadoc, you can use the constructor to specify whether you want to append or not. Constructs a FileWriter object given a File object. If the second argument is true, then bytes will be written to the end of the file rather than the beginning.
FileWriter class is used for writing streams of characters. FileWriter takes an optional second parameter: append . If set to true, then the data will be written to the end of the file. This example appends data to a file with FileWriter .
When you create a Java FileWriter you can decide if you want to overwrite any existing file with the same name, or if you want to append to any existing file. You decide that by choosing what FileWriter constructor you use.
Using FileOutputStream FileOutputStream is meant for writing streams of raw bytes such as image data. For writing streams of characters, consider using FileWriter . To append content to an existing file, open FileOutputStream in append mode by passing the second argument as true .
Pass true
as a second argument to FileWriter
to turn on "append" mode.
fout = new FileWriter("filename.txt", true);
FileWriter usage reference
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