Tap*_*ose 16 java nio image inputstream 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();
}
Run Code Online (Sandbox Code Playgroud)
我想知道这是否是使用NIO的正确方法.我读过一个方法FileChannel.transferFrom,它有三个参数:
在我的情况下,我只有src,我没有position和count,有什么办法可以使用这种方法来创建文件?
另外对于Image有没有更好的方法来创建只有InputStreamNIO的图像?
任何信息对我都非常有用.这里有类似的问题,在SO中,但我找不到适合我的案例的特定解决方案.
Evg*_*eev 45
我会使用Files.copy
Files.copy(is, Paths.get(filePath));
Run Code Online (Sandbox Code Playgroud)
至于你的版本
ByteBuffer.allocateDirect更快 - Java将尽最大努力直接执行本机I/O操作.
关闭是不可靠的,如果第一次失败,则第二次永远不会执行.使用try-with-resources代替,频道也是AutoCloseable如此.
不,这不正确.您冒着丢失数据的风险.规范的NIO复制循环如下:
while (in.read(buffer) >= 0 || buffer.position() > 0)
{
buffer.flip();
out.write(buffer);
buffer.compact();
}
Run Code Online (Sandbox Code Playgroud)
注意改变的循环条件,它负责在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;
}
Run Code Online (Sandbox Code Playgroud)
它必须在循环中调用,因为它不能保证传输整个量子.
| 归档时间: |
|
| 查看次数: |
27059 次 |
| 最近记录: |