How to use NIO to write InputStream to File?

后端 未结 2 1182
-上瘾入骨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.

    0 讨论(0)
  • 2021-02-05 10:07

    No it's not correct. You run the risk of losing data. The canonical NIO copy loop is as follows:

    while (in.read(buffer) >= 0 || buffer.position() > 0)
    {
      buffer.flip();
      out.write(buffer);
      buffer.compact();
    }
    

    Note the changed loop conditions, which take care of flushing the output at EOS, and the use of compact() instead of clear(), which takes care of the possibility of short writes.

    Similarly the canonical transferTo()/transferFrom() loop is as follows:

    long offset = 0;
    long quantum = 1024*1024; // or however much you want to transfer at a time
    long count;
    while ((count = out.transferFrom(in, offset, quantum)) > 0)
    {
        offset += count;
    }
    

    It must be called in a loop, as it isn't guaranteed to transfer the entire quantum.

    0 讨论(0)
提交回复
热议问题