Dumping a Java StringBuilder to File

前端 未结 9 600
南旧
南旧 2021-02-01 14:17

What is the most efficient/elegant way to dump a StringBuilder to a text file?

You can do:

outputStream.write(stringBuilder.toString().getBytes());
         


        
9条回答
  •  闹比i
    闹比i (楼主)
    2021-02-01 14:36

    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.

提交回复
热议问题