Dumping a Java StringBuilder to File

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

    You should use a BufferedWriter to optimize the writes (always write character data using a Writer instead of an OutputStream). If you weren't writing character data, you would use a BufferedOutputStream.

    File file = new File("path/to/file.txt");
    BufferedWriter writer = null;
    try {
        writer = new BufferedWriter(new FileWriter(file));
        writer.write(stringBuilder.toString());
    } finally {
        if (writer != null) writer.close();
    }
    

    or, using try-with-resources (Java 7 and up)

    File file = new File("path/to/file.txt");
    try (BufferedWriter writer = new BufferedWriter(new FileWriter(file))) {
        writer.write(stringBuilder.toString());
    }
    

    Since you're ultimately writing to a file, a better approach would be to write to the BufferedWriter more often instead of creating a huge StringBuilder in-memory and writing everything at the end (depending on your use-case, you might even be able to eliminate the StringBuilder entirely). Writing incrementally during processing will save memory and will make better use of your limited I/O bandwidth, unless another thread is trying to read a lot of data from the disk at the same time you're writing.

提交回复
热议问题