Dumping a Java StringBuilder to File

前端 未结 9 727
南旧
南旧 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:29

    As pointed out by others, use a Writer, and use a BufferedWriter, but then don't call writer.write(stringBuilder.toString()); instead just writer.append(stringBuilder);.

    EDIT: But, I see that you accepted a different answer because it was a one-liner. But that solution has two problems:

    1. it doesn't accept a java.nio.Charset. BAD. You should always specify a Charset explicitly.

    2. it's still making you suffer a stringBuilder.toString(). If the simplicity is really what you're after, try the following from the Guava project:

    Files.write(stringBuilder, file, Charsets.UTF_8)

提交回复
热议问题