Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 688
KiKi Avatar asked Jul 08 '11 02:07

KiKi


People also ask

What is a FileChannel?

A file channel is a SeekableByteChannel that is connected to a file. It has a current position within its file which can be both queried and modified . The file itself contains a variable-length sequence of bytes that can be read and written and whose current size can be queried.

What is FileChannel in Java?

In general we can say that FileChannel is a channel that is connected to a file by which you can read data from a file, and write data to a file. Other important characteristic of FileChannel is this that it cannot be set into non-blocking mode and always runs in blocking mode.


2 Answers

Channels.newChannel(InputStream in)

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

like image 93
Kal Avatar answered Oct 20 '22 22:10

Kal


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

like image 30
Amlan Chatterjee Avatar answered Oct 20 '22 23:10

Amlan Chatterjee