Dumping a Java StringBuilder to File

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

    Benchmarks for most answers here + improved implementation: https://www.genuitec.com/dump-a-stringbuilder-to-file/

    The final implementation is along the lines of

    try {
        BufferedWriter bw = new BufferedWriter(
                new OutputStreamWriter(
                        new FileOutputStream(file, append), charset), BUFFER_SIZE);
        try {
            final int length = sb.length();
            final char[] chars = new char[BUFFER_SIZE];
            int idxEnd;
            for ( int idxStart=0; idxStart

提交回复
热议问题