Best way to write String to file using java nio

后端 未结 5 1926
清歌不尽
清歌不尽 2021-01-30 12:49

I need to write(append) huge string to flat file using java nio. The encoding is ISO-8859-1.

Currently we are writing as shown below. Is there any better

5条回答
  •  终归单人心
    2021-01-30 13:29

    UPDATED:

    Since Java11 there is a specific method to write strings using java.nio.file.Files:

    Files.writeString(Paths.get(file.toURI()), "My string to save");
    

    We can also customize the writing with:

    Files.writeString(Paths.get(file.toURI()), 
                      "My string to save", 
                       StandardCharsets.UTF_8,
                       StandardOpenOption.CREATE,
                       StandardOpenOption.TRUNCATE_EXISTING);
    

    ORIGINAL ANSWER:

    There is a one-line solution, using Java nio:

    java.nio.file.Files.write(Paths.get(file.toURI()), 
                              "My string to save".getBytes("utf-8"),
                              StandardOpenOption.CREATE,
                              StandardOpenOption.TRUNCATE_EXISTING);
    

    I have not benchmarked this solution with the others, but using the built-in implementation for open-write-close file should be fast and the code is quite small.

提交回复
热议问题