What is the most efficient/elegant way to dump a StringBuilder to a text file?
You can do:
outputStream.write(stringBuilder.toString().getBytes());
Well, if the string is huge, toString().getBytes()
will create duplicate bytes (2 or 3 times). The size of the string.
To avoid this, you can extract chunk of the string and write it in separate parts.
Here is how it may looks:
final StringBuilder aSB = ...;
final int aLength = aSB.length();
final int aChunk = 1024;
final char[] aChars = new char[aChunk];
for(int aPosStart = 0; aPosStart < aLength; aPosStart += aChunk) {
final int aPosEnd = Math.min(aPosStart + aChunk, aLength);
aSB.getChars(aPosStart, aPosEnd, aChars, 0); // Create no new buffer
final CharArrayReader aCARead = new CharArrayReader(aChars); // Create no new buffer
// This may be slow but it will not create any more buffer (for bytes)
int aByte;
while((aByte = aCARead.read()) != -1)
outputStream.write(aByte);
}
Hope this helps.