What is the most efficient/elegant way to dump a StringBuilder to a text file?
You can do:
outputStream.write(stringBuilder.toString().getBytes());
But is this efficient for a very long file?
Is there a better way?
解决方案
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:
it doesn't accept a java.nio.Charset. BAD. You should always specify a Charset explicitly.
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:
博客探讨了将StringBuilder内容写入文本文件的高效优雅方式。提出可使用outputStream.write(stringBuilder.toString().getBytes()),但对长文件效率存疑。解决方案建议用Writer和BufferedWriter,直接writer.append(stringBuilder),还指出其他方案存在不支持指定字符集和需调用toString方法的问题。
1129

被折叠的 条评论
为什么被折叠?



