Reputation: 1
I am trying to write timestamps to a file when clicking on a JButton. Once .close()
is invoked the data is written to the file and any other writes throw an error. How can I write the data without have to create a new FileWriter and overwriting the previous line?
Upvotes: 0
Views: 3767
Reputation: 33544
Try this,
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
public class Wr {
public static void main(String[] args) throws IOException {
File f = new File("viv.txt");
FileWriter fw = new FileWriter(f, true);
BufferedWriter bw = new BufferedWriter(fw);
bw.write("Helloooooooooo");
bw.close();
}
}
Upvotes: 0
Reputation:
You can either keep the writer open between clicks and close it at some other time (perhaps on form exit), or you can create a new FileWriter for each click and have it append to contents already in the file.
FileWriter writer = new FileWriter("output.txt", true); //true here indicates append to file contents
If you choose to keep the writer open between clicks, then you might want to call .flush() on each button press to make sure the file is up to date.
Upvotes: 0
Reputation: 13936
Instead of closing, which does this implictly, you call flush()
on the FileWriter
object. That keeps it open, but forces the data which has been buffered to be written to the file.
Don't forget to close()
when you are done writing though.
Upvotes: 3