簡體   English   中英

如何使用NIO將InputStream寫入File?

[英]How to use NIO to write InputStream to File?

我使用以下方式將InputStream寫入File

private void writeToFile(InputStream stream) throws IOException {
    String filePath = "C:\\Test.jpg";
    FileChannel outChannel = new FileOutputStream(filePath).getChannel();       
    ReadableByteChannel inChannel = Channels.newChannel(stream);
    ByteBuffer buffer = ByteBuffer.allocate(1024);

    while(true) {
        if(inChannel.read(buffer) == -1) {
            break;
        }

        buffer.flip();
        outChannel.write(buffer);
        buffer.clear();
    }

    inChannel.close();
    outChannel.close();
}

我想知道這是否是使用NIO的正確方法。 我讀過一個方法FileChannel.transferFrom ,它有三個參數:

  1. ReadableByteChannel src
  2. 多頭頭寸
  3. 長計數

在我的情況下,我只有src ,我沒有positioncount ,有什么方法可以使用此方法來創建文件?

另外對於Image,還有更好的方法只能從InputStream和NIO創建圖像嗎?

任何信息對我都非常有用。 這里有類似的問題,在SO中,但我找不到適合我的案例的特定解決方案。

我會使用Files.copy

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

至於你的版本

  1. ByteBuffer.allocateDirect更快 - Java將盡最大努力直接執行本機I / O操作。

  2. 關閉是不可靠的,如果第一次失敗,則第二次永遠不會執行。 使用try-with-resources代替,Channels也是AutoCloseable

不,這不正確。 您冒着丟失數據的風險。 規范的NIO復制循環如下:

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

注意改變的循環條件,它負責在EOS上刷新輸出,並使用compact()而不是clear(),來處理短寫入的可能性。

類似地,規范transferTo()/transferFrom()循環如下:

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;
}

它必須在循環中調用,因為它不能保證傳輸整個量子。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM