Updated August 29, 2023
Definition of Java NIO FileChannel
Java NIO (New Input/Output) FileChannel is a class in the Java programming language that provides a channel-based approach to perform I/O operations on a file.
Java NIO FileChannel is part of the Java NIO package and was introduced in Java 1.4 as an alternative to the traditional I/O API for performing file operations.
FileChannel provides methods for reading and writing data from a file, mapping a file into memory, locking a portion of the file, and transferring data between channels. The channel-based approach provided by FileChannel is more efficient and flexible than the traditional I/O API, as it allows for asynchronous I/O operations and better control over buffer management.
A Java NIO FileChannel is a channel associated with a file. You can read and write data to and from files using a filechannel. The Java NIO FileChannel class is NIO’s replacement for the native Java IO API for reading files. You cannot switch a FileChannel to non-blocking mode.
Table of Contents
What is Java NIO FileChannel?
In Java NIO FileChannel, the channel effectively moves data between byte and entity buffers. The system captures data from an object and stores it in buffer blocks for subsequent use. To access the I/O mechanism, Java NIO provides channels as a gateway. FileChannel offers several advantages over the traditional Java I/O streams. It is non-blocking, meaning it can perform I/O operations asynchronously, allowing for better performance and responsiveness. It provides a powerful and efficient way to work with files in Java, especially when dealing with large files or when performance is critical.
Key Takeaways
- Reading and writing in a specific file place.
- Directly loading a file chunk into memory is sometimes more effective.
- Data can be transferred more quickly from one channel to another.
- We can secure a file’s section to prevent other threads from accessing it.
- You can force modifications to a file to be promptly stored to prevent data loss.
How to Create Java NIO FileChannel?
1. Input document
The existing text file has the information: 1234567890
2. Construct a channel
To create a channel, utilize the filechannel’s static open() method. The method accesses the specified file by opening it and returns a FileChannel.
Code:
Path file_path = Paths.get("filename.txt");
FileChannel fileChannel_var = FileChannel.open(file_path);
3. Build a buffer
Use the ByteBuffer’s allocate() static function to create a ByteBuffer. The new buffer’s elements will all have their position, limit, and initialization set to zero. This illustration sets the initial capacity at six.
ByteBuffer buffer_variable = ByteBuffer.allocate(6);
4. Operate file data
To write and read data, utilize “opening filechannel models”. We can manage data using various models. For example, we can read the file data.
int numberOfBytes = fileChannel.read(buffer_variable);
5. Display the contents of the buffer
The buffer’s clean() method prepares the buffer for a new channel read sequence by setting the position to 0 and the limit to the capacity (6).
while (buffer_variable.hasRemaining()) {
System.out.print((char) buffer_variable.get());
}
6. Close
This channel is closed by the filechannel’s close() method.
IOException is thrown by the open(), shut(), position(), and read() methods of FileChannel in the sample.
Reading Files using FileChannel
When we read a huge file, FileChannel performs better than ordinary I/O. It’s important to remember that despite being a component of Java NIO, FileChannel functions are blocking and without a non-blocking option.
Code:
@Test
public void readFilewithNioFileChannel()
throws IOException {
try (RandomAccessFile reader_data = new RandomAccessFile("filepath/filename.in", "r");
FileChannel channel _data = reader_data.getChannel();
ByteArrayOutputStream out_value = new ByteArrayOutputStream()) {
int bufferSize = 1024;
if (bufferSize > channel_data.size()) {
bufferSize = (int) channel_data.size();
}
ByteBuffer buffer_var = ByteBuffer.allocate(bufferSize);
while (channel_data.read(buffer_var) > 0) {
cout_value.write(buffer_var.array(), 0, buffer_var.position());
buffer_var.clear();
}
String file_values = new String(cout_value.toByteArray(), StandardCharsets.UTF_8);
assertEquals("Hello Student", file_values);
}
}
Writing Files using FileChannel
Use the following syntax for writing data using FileChannel.
Code:
@Test
public void writeFilesUsingFileChannel()
throws IOException {
String file_var = "file_path / filename.txt";
try (RandomAccessFile writer = new RandomAccessFile(file_var, "rw");
FileChannel channel_var = writer.getChannel()){
ByteBuffer buffer_var = ByteBuffer.wrap("Hello world".getBytes(StandardCharsets.UTF_8));
channel_var.write(buffer_var);
RandomAccessFile reader_data = new RandomAccessFile(file_var, "r");
assertEquals("Hello Student", reader_data.readLine());
reader_data.close();
}
}
Opening a FileChannel Model
The file should be opened in read/write mode (Opening a FileChannel)
A FileChannel must be obtained via an InputStream, OutputStream, or RandomAccessFile.
1. Opening a FileChannel for reading file
The model uses the “r” with the given file for the reading file of the fileChannel. The “RandomAccessFile” is used with the file and reading filechannel keyword.
RandomAccessFile writer = new RandomAccessFile(file_var, "r");
FileChannel channel_var = writer.getChannel();
2. Opening a FileChannel for writing file
The model uses the “rw” with the given file for the writing file of the fileChannel. The “RandomAccessFile” is used with the file and writing filechannel keyword.
RandomAccessFile writer = new RandomAccessFile(file_var, "rw");
FileChannel channel_var = writer.getChannel();
Position of Java NIO FileChannel
You always start writing or reading to a FileChannel at a particular place. Implementing the position() method will return the FileChannel object’s current location. By invoking the position(long pos) method, you can also modify the FileChannel’s position.
Here are the methods of the fileChannel position’s examples:
long position_var channel.position();
channel.position(position_var +123);
You will receive -1, the end-of-file marker, if you specify the starting point at the end of the file and attempt to get data from the channel.
If you specify the position after the end of the file and use the channel to write to it, the file will be enlarged to accommodate the position and any written data.
Examples
The “inputfile.txt” is a file to read, write, and operate using the fileChannel model. The file contains the “Hello Students!” data to read and operate.
Example 1
The following example shows available data in the file. It is used to read files using filechannel.
Code:
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.Charset;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.HashSet;
import java.util.Set;
public class FileChannelWritingDemo {
public static void main(String args[]) throws IOException {
readNioFileChannel();
}
public static void readNioFileChannel() throws IOException {
RandomAccessFile ranAccessVar = new RandomAccessFile("C:/Demo/inputfile.txt",
"rw");
FileChannel fileOpChannel = ranAccessVar.getChannel();
ByteBuffer bufVar = ByteBuffer.allocate(512);
Charset charset_var = Charset.forName("US-ASCII");
while (fileOpChannel.read(bufVar) > 0) {
bufVar.rewind();
System.out.print(charset_var.decode(bufVar));
bufVar.flip();
}
fileOpChannel.close();
ranAccessVar.close();
}
}
Output:
Example 2
The following example shows the file’s available data with operated information.
Code:
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.Charset;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.HashSet;
import java.util.Set;
public class FileChannelWritingDemo {
public static void main(String args[]) throws IOException {
//Write the information to the existing file
writeNioFileChannel(ByteBuffer.wrap("Welcome to Java NIO Tutorial".getBytes()));
//read the required file
readNioFileChannel();
}
public static void readNioFileChannel() throws IOException {
RandomAccessFile randomAccVar = new RandomAccessFile("C:/Demo/inputfile.txt",
"rw");
FileChannel fileOpChannel = randomAccVar.getChannel();
ByteBuffer bufVar = ByteBuffer.allocate(512);
Charset charset_var = Charset.forName("US-ASCII");
while (fileOpChannel.read(bufVar) > 0) {
bufVar.rewind();
System.out.print(charset_var.decode(bufVar));
bufVar.flip();
}
fileOpChannel.close();
randomAccVar.close();
}
public static void writeNioFileChannel(ByteBuffer bufVar)throws IOException {
Set<StandardOpenOption> options_info = new HashSet<>();
options_info.add(StandardOpenOption.CREATE);
options_info.add(StandardOpenOption.APPEND);
Path path_var = Paths.get("C:/Demo/inputfile.txt");
FileChannel fileOpChannel = FileChannel.open(path_var, options_info);
fileOpChannel.write(bufVar);
fileOpChannel.close();
}
}
Output
Conclusion
Java NIO FileChannel is a powerful tool for reading and writing files in Java. It provides a more efficient way of handling large files and allows for non-blocking I/O operations. Additionally, the flexibility of opening a filechannel in different modes makes it easy to customize your implementation based on your specific needs. Mastering Java NIO FileChannel can significantly enhance your programming skills and help you create more efficient and effective applications.
You have seen how to read and write data using FileChannel. You have also seen the use of FileChannels in concurrent or data-critical applications, as well as how to read and update the file size and its current read/write location.
Recommended Article
We hope that this EDUCBA information on “Java NIO FileChannel” was beneficial to you. You can view EDUCBA’s recommended articles for more information.