How to use NIO to write InputStream to File?

后端 未结 2 1186
-上瘾入骨i
-上瘾入骨i 2021-02-05 09:03

I am using following way to write InputStream to File:

private void writeToFile(InputStream stream) throws IOException {
    String file         


        
2条回答
  •  你的背包
    2021-02-05 09:57

    I would use Files.copy

    Files.copy(is, Paths.get(filePath));
    

    as for your version

    1. ByteBuffer.allocateDirect is faster - Java will make a best effort to perform native I/O operations directly upon it.

    2. Closing is unreliable, if first fails second will never execute. Use try-with-resources instead, Channels are AutoCloseable too.

提交回复
热议问题