Dumping a Java StringBuilder to File

前端 未结 9 605
南旧
南旧 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条回答
  • 2021-02-01 14:36

    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.

    0 讨论(0)
  • 2021-02-01 14:39

    If the string itself is long, you definitely should avoid toString(), which makes another copy of the string. The most efficient way to write to stream should be something like this,

    OutputStreamWriter writer = new OutputStreamWriter(
            new BufferedOutputStream(outputStream), "utf-8");
    
    for (int i = 0; i < sb.length(); i++) {
        writer.write(sb.charAt(i));
    }
    
    0 讨论(0)
  • 2021-02-01 14:40

    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);
            }
        }
    }
    
    0 讨论(0)
提交回复
热议问题