What is the most efficient/elegant way to dump a StringBuilder to a text file?
You can do:
outputStream.write(stringBuilder.toString().getBytes());
But is this efficient for a very long file?
Is there a better way?
What is the most efficient/elegant way to dump a StringBuilder to a text file?
You can do:
outputStream.write(stringBuilder.toString().getBytes());
But is this efficient for a very long file?
Is there a better way?
Since java 8 you only need to do this:
Files.write(Paths.get("/path/to/file/file_name.extension"), stringBuilder.toString().getBytes());
You don't need any third party libraries to do that.
Based on https://stackoverflow.com/a/1677317/980442
I create this function that use OutputStreamWriter and the write(), this is memory optimized too, better than just use StringBuilder.toString().
public static void stringBuilderToOutputStream(
StringBuilder sb, OutputStream out, String charsetName, int buffer)
throws IOException {
char[] chars = new char[buffer];
try (OutputStreamWriter writer = new OutputStreamWriter(out, charsetName)) {
for (int aPosStart = 0; aPosStart < sb.length(); aPosStart += buffer) {
buffer = Math.min(buffer, sb.length() - aPosStart);
sb.getChars(aPosStart, aPosStart + buffer, chars, 0);
writer.write(chars, 0, buffer);
}
}
}