I'm working on a project where I need to print some data to a file. During debugging phase, I would like to overwrite the old textfile so that I don't have to delete the old file just to see the result of some changes that I've made in the code. Currently, the new output data is either added to the old data in the file, or the file doesn't change at all (also, why could this be?). The following is, in essence, the printing part of the code:
public class Test {
public static void main(String[] arg) {
PrintWriter pw = null;
try {
pw = new PrintWriter(new FileOutputStream("Foo.txt", true));
} catch (Exception e){}
double abra = 5;
double kadabra = 7;
pw.printf("%f %f \n", abra, kadabra);
pw.close();
}
}
Thanks!
Simply pass second parameter false.
Also you can use other writer object instead of FileOutputStream as you are working with txt file. e.g
pw = new PrintWriter(new FileWriter("Foo.txt", false));
or
pw = new PrintWriter(new BufferedWriter(new FileWriter("Foo.txt", false)));
while working with txt/docs files we should go for normal writer objects( FileWriter
or BufferedWriter
) and while working with binary file like .mp3 , image, pdf we should go for Streams ( FileOutputStream
or OutputStreamWriter
).
Pass false
to the append
parameter to overwrite the file:
pw = new PrintWriter(new FileOutputStream("Foo.txt", false));
Passing true
for the second parameter indicates that you want to append to the file; passing false
means that you want to overwrite the file.
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