What is the most efficient/elegant way to dump a StringBuilder to a text file?
You can do:
outputStream.write(stringBuilder.toString().getBytes());
For character data better use Reader/Writer
. In your case, use a BufferedWriter
. If possible, use BufferedWriter
from the beginning on instead of StringBuilder
to save memory.
Note that your way of calling the non-arg getBytes()
method would use the platform default character encoding to decode the characters. This may fail if the platform default encoding is for example ISO-8859-1
while your String data contains characters outside the ISO-8859-1
charset. Better use the getBytes(charset)
where in you can specify the charset yourself, such as UTF-8
.