我使用下面的方法来写InputStream
到File
:如何使用NIO将InputStream写入文件?
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
,有没有什么办法可以使用这种方法来创建文件?
也为图像有没有更好的方式来创建图像只从InputStream
和NIO?
任何信息对我来说都是非常有用的。在这里也有类似的问题,但我无法找到适合我的案例的任何特定解决方案。
为什么这么复杂?你可以在一行中做同样的事情:'Files.copy(stream,new File(“C:\\ Test.jpg”)。toPath());' – Jesper