Dumping a Java StringBuilder to File

前端 未结 9 736
南旧
南旧 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
    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));
    }
    

提交回复
热议问题