I’ve been working on sort of “logging” to text file using BufferedWriter and I came across a problem:
I run the following code.. fairly basic..
BufferedWriter out = new BufferedWriter(new FileWriter(path+fileName));
String str = "blabla";
out.write(str);
out.close();
and the next thing I know is that the entire file that had couple of lines of text has been cleared and only ‘blabla’ is there.
What class should I use to make it add a new line, with the text ‘blabla’, without having to get the entire file text to a string and adding it to ‘str’ before ‘blabla’?
You’re using the right classes (well, maybe – see below) – you just didn’t check the construction options. You want the
FileWriter(String, boolean)constructor overload, where the second parameter determines whether or not to append to the existing file.However:
FileWriterin general anyway, as you can’t specify the encoding. Annoying as it is, it’s better to useFileOutputStreamand wrap it in anOutputStreamWriterwith the right encoding.Rather than using
path + fileNameto combine a directory and a filename, useFile:That lets the core libraries deal with different directory separators etc.
finallyblock (so that you clean up even if an exception is thrown), or a “try-with-resources” block if you’re using Java 7.So putting it all together, I’d use: