将Java StringBuilder转储到文件 [英] Dumping a Java StringBuilder to File
问题描述
将StringBuilder转储到文本文件中最有效/最优雅的方法是什么?
What is the most efficient/elegant way to dump a StringBuilder to a text file?
您可以这样做:
outputStream.write(stringBuilder.toString().getBytes());
但这对于很长的文件有效吗?
But is this efficient for a very long file?
有更好的方法吗?
推荐答案
正如其他人所指出的,请使用Writer和BufferedWriter,但不要调用writer.write(stringBuilder.toString());
而不是writer.append(stringBuilder);
.
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);
.
但是,我看到您接受了一个不同的答案,因为它是单线的.但是该解决方案有两个问题:
But, I see that you accepted a different answer because it was a one-liner. But that solution has two problems:
-
它不接受
java.nio.Charset
.坏的.您应该始终明确指定一个字符集.
it doesn't accept a
java.nio.Charset
. BAD. You should always specify a Charset explicitly.
它仍然使您遭受stringBuilder.toString()
痛苦.如果真的很简单,请从 Guava 项目中尝试以下操作:
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: