Reputation: 3015
I am using two FileWriter
s after each other.
The first one does not append
BufferedWriter versionWriter = new BufferedWriter(new FileWriter(new File(filePath)));
versionWriter.write(s);
versionWriter.close();
whereas I would like the one after to append.
BufferedWriter bw = new BufferedWriter(new FileWriter(new File(filePath), true));
bw.newLine();
bw.write(s);
The problem is that my first FileWriter
destroys the whole file, therefore making me lose my data.
The reason I am doing using two FileWriter
s is that the first one is supposed to overwrite the first line of my textfile, whereas the second one is supposed to append to the end of the file.
What is the correct way to do this?
Edit: I realise it is possible to first read everything and then save it back, but this is highly inefficient, especially since I will need to store a lot of data in the file.
Upvotes: 0
Views: 63
Reputation: 3033
Use RandomAccessFile.seek(...) to write data into a file at a specific position.
But there's no magic to "replace the first line of file" apart from reading into memory, replace the first line and writing out to file again. Unless that line always has the very same length. And you take care not to overwrite the EOL character. :-)
Btw, don't forget to call flush() before closing.
Upvotes: 2