Reputation: 141
import java.io.FileWriter;
import java.io.PrintWriter;
public class DemoPrint {
public static void main (String args []) {
try{
PrintWriter coolFile = new PrintWriter("c:\\JavaIO\\cool.txt");
FileWriter file = new FileWriter("c:\\JavaIO\\cool.txt", true);
coolFile.println("Why isn't this adding another line?");
coolFile.close();
}
catch (Exception e) {
System.out.println("Error");
}
}
}
So I'm new to programming/java and I'm trying to open this file and append the data and add another line but for some reason the data is just being erased and overwritten with whatever I have in the coolFile.println("")
.
Can anyone help me out on this? I know its probably a easy fix... I'm learning.. Thank you!
Upvotes: 1
Views: 26
Reputation: 34628
You are opening both a PrintWriter
and a FileWriter
on the same file. The two are not related to each other - they are two points of access to the same file (which is something you really shouldn't do).
The opening of the PrintWriter
has already been done without appending, and therefore, it destroyed all the content of the file. Then you go and open another "view" on it - a FileWriter
, and it's set to append, but at this point, it no longer has anything to append to.
The proper way is to create the PrintWriter
so that it is backed by the FileWriter
. Not two views on the file - one view that rides on another view.
PrintWriter coolFile = new PrintWriter( new FileWriter("filename", true ) );
Upvotes: 4