简体   繁体   中英

Using FileChannel to write any InputStream?

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM