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:
- I'd recommend against
FileWriter
in general anyway, as you can't specify the encoding. Annoying as it is, it's better to use FileOutputStream
and wrap it in an OutputStreamWriter
with the right encoding.
Rather than using path + fileName
to combine a directory and a filename, use File
:
new File(path, fileName);
That lets the core libraries deal with different directory separators etc.
- Make sure you close your output using a
finally
block (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:
String encoding = "UTF-8"; // Or use a Charset
File file = new File(path, fileName);
BufferedWriter out = new BufferedWriter(
new OutputStreamWriter(new FileOutputStream(file, true), encoding));
try {
out.write(...);
} finally {
out.close()'
}