Using FileChannel to write any InputStream?

和自甴很熟 提交于 2019-12-30 04:15:39

问题


Can I write any InputStream into a FileChannel?

I'm using java.nio.channels.FileChannel to open a file and lock it, then writing a InputStream to the output file. The InputStream may be opened by another file, URL, socket, or anything. I've write the following codes:

FileOutputStream outputStream = new FileOutputStream(outputFile);
FileChannel outputChannel = outputStream.getChannel();
FileLock lock = outputChannel.lock();
try {
    outputChannel.transferFrom(???);
} finally {
    lock.release();
    outputChannel.close();
    outputStream.close();
}

However, the first argument of outputChannel.transferFrom(...) requests a ReadableByteChannel object. Since I an using a InputStream as input, it do not have inputStream.getChannel() method to create the required channel.

Is there any way to get a ReadableByteChannel from a InputStream?


回答1:


Channels.newChannel(InputStream in)

http://docs.oracle.com/javase/7/docs/api/java/nio/channels/Channels.html




回答2:


You can use ReadableByteChannel readableChannel = Channels.newChannel(myinputstream).



来源:https://stackoverflow.com/questions/6619516/using-filechannel-to-write-any-inputstream

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!