如何使用NIO将InputStream写入File? [英] How to use NIO to write InputStream to File?

查看:987
本文介绍了如何使用NIO将InputStream写入File?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用以下方式将 InputStream 写入文件

I am using following way to write InputStream to 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 ,它带有三个参数:

I was wondering if this is the right way to use NIO. I have read a method FileChannel.transferFrom, which takes three parameter:


  1. ReadableByteChannel src

  2. 多头头寸

  3. 长计数

在我的情况下我只有 src ,我没有位置 count ,有什么办法可以用这个方法创建文件吗?

In my case I only have src, I don't have the position and count, is there any way I can use this method to create the file?

for Image有没有更好的方法只从 InputStream 和NIO创建图像?

Also for Image is there any better way to create image only from InputStream and NIO?

任何信息都非常有用对我来说。这里有类似的问题,在SO中,但我找不到适合我的特定解决方案。

Any information would be very useful to me. There are similar questions here, in SO, but I cannot find any particular solution which suites my case.

推荐答案

不,这不正确。您冒着丢失数据的风险。规范的NIO复制循环如下:

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

注意改变的循环条件,它负责刷新EOS的输出,并使用 compact()而不是 clear(),来处理短写的可能性。

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.

同样规范的 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;
}

必须在循环中调用它,因为它不能保证传输整个量子。

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

这篇关于如何使用NIO将InputStream写入File?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆