开发者

Using FileChannel to write any InputStream?

开发者 https://www.devze.com 2023-03-18 16:59 出处:网络
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 an

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 anoth开发者_如何学Pythoner 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?


Channels.newChannel(InputStream in)

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


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

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号