【发布时间】:2013-05-11 00:13:20
【问题描述】:
我正在使用以下方式将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,它需要三个参数:
- ReadableByteChannel src
- 多头
- 长计数
就我而言,我只有src,我没有position 和count,有什么方法可以使用这种方法来创建文件吗?
对于 Image 还有没有更好的方法来仅从 InputStream 和 NIO 创建图像?
任何信息都会对我非常有用。这里有类似的问题,在 SO 中,但我找不到适合我的情况的任何特定解决方案。
【问题讨论】:
-
为什么要这么复杂?您可以在一行中执行相同的操作:
Files.copy(stream, new File("C:\\Test.jpg").toPath());
标签: java image file inputstream nio