如何使用NIO将输入流写入文件?
2022-09-02 05:10:52
						我使用以下方式写到:InputStreamFile
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,它采用三个参数:
- 可读字节通道 src
 - 多头仓位
 - 长计数
 
在我的情况下,我只有,我没有和,有没有办法使用这种方法来创建文件?srcpositioncount
另外,对于图像,有没有更好的方法只从和NIO创建图像?InputStream
任何信息对我来说都非常有用。在SO中,这里有类似的问题,但我找不到任何适合我情况的特定解决方案。