Best way to write String to file using java nio

后端 未结 5 1973
清歌不尽
清歌不尽 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条回答
  •  萌比男神i
    2021-01-30 13:56

    A BufferedWriter around a FileWriter will almost certainly be faster than any NIO scheme you can come up with. Your code certainly isn't optimal, with a new ByteBuffer per write, and then doing pointless operations on it when it is about to go out of scope, but in any case your question is founded on a misconception. NIO doesn't 'offload the memory footprint to the OS' at all, unless you're using FileChannel.transferTo/From(), which you can't in this instance.

    NB don't use a PrintWriter as suggested in comments, as this swallows exceptions. PW is really only for consoles and log files where you don't care.

提交回复
热议问题