Java - File Input Output Channels

Introduction

A channel is an open connection between a data source and a Java program.

The Channel interface in the java.nio.channels package represents channels in Java.

To obtain a channel, create an object of InputStream and OutputStream.

Create

Utility Channels class converts streams into channels and vice versa.

The following code gets a ReadableByteChannel from input stream object

// Get a ReadableByteChannel from an InputStream
ReadableByteChannel rbc = Channels.newChannel(myInputStream);

Obtain the underlying InputStream object

// Get the InputStream of the ReadableByteChannel
InputStream myInputStream = Channels.newInputStream(rbc);

FileInputStream and FileOutputStream classes have a new method called getChannel() to return a FileChannel object.

A FileChannel is used to read and write data to a file.

The FileChannel object obtained from a FileInputStream is opened in a read-only mode.

The FileChannel object obtained from a FileOutputStream object is opened in a write-only mode.

The FileChannel from a RandomAccessFile is opened in a read-only, write-only, or read-write mode, depending on the way you create that RandomAccessFile object.

Exmple

The following code obtains FileChannel objects for different kinds of file streams:

FileInputStream fis = new FileInputStream("Main.java");
FileChannel fcReadOnly = fis.getChannel(); // A read-only channel

FileOutputStream fos = new FileOutputStream("Main.java");
FileChannel fcWriteOnly = fos.getChannel(); // A write-only channel

// Open file in a read-only mode
RandomAccessFile raf1 = new RandomAccessFile("Main.java", "r");
FileChannel rafReadOnly = raf1.getChannel(); // A read-only channel

// Open file in a read-write mode
RandomAccessFile raf2 = new RandomAccessFile("Main.java", "rw");
FileChannel rafReadWrite = raf2.getChannel(); // A read-write channel

You can get a FileChannel using the FileChannel.open() static method.

Related Topics