Using FileChannel to write any InputStream?

Is it possible to write an InputStream in a FileChannel?

I use java.nio.channels.FileChannel to open a file and lock it, and then write an InputStream to the output file. An InputStream can be opened by another file, URL, socket, or anything else. I am writing 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 to outputChannel.transferFrom (...) requests the ReadableByteChannel object. Since I use InputStream as input, it does not have an inputStream.getChannel () method to create the required channel.

Is there any way to get ReadableByteChannel from InputStream?

+6
source share
2 answers
+17
source

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

+5
source

Source: https://habr.com/ru/post/892289/


All Articles