Java Filechannel (2024)
In this tutorial, will look at the Java NIO FileChannel. We'll also learn the basics required to understand File Channel.
There are two ways, in which we can read the file, it could be sequentially or randomly. To read file sequentially, it's called Sequential Files, whereas reading randomly from the file called Random Access Files (RAFs).
In RAFs, we can perform many operations like open a file, read/write, seek particular location, read chunk of bytes/line/portion, append/delete lines etc. FileChannel was introduced in Java 4 and later Java added feature called SeekableByteChannel to
support RAFs operations. Also added feature to load the particular region/portion of a file into memory and which can be accessed later. This is very useful, when we want to read the content multiple times.
Now let's see
FileChannel, A Java NIO FileChannel is a channel that is connected to a file. Using a file channel you can read data from a file, and write data to a file.
Note: File Channel is thread safe, as read/write can be done asynchronously, only one thread can update file data at a time.
Lets' explore read/write operation on file using NIO FileChannel.
Open the file in read/write mode (Opening a FileChannel)
You need to obtain a FileChannel via an InputStream, OutputStream, or a RandomAccessFile. Here is how you open a FileChannel via a RandomAccessFile:
RandomAccessFile dataFile = new RandomAccessFile("resources/nio-notes-data.txt", "rw");
FileChannel fileReadWriteChannel = dataFile.getChannel();
- Reading a file Using FileChannel
- Write Data Using FileChannel :
- FileChannel operations :
ByteBuffer buff = ByteBuffer.allocate(1024);
int notesBytesRead = fileReadWriteChannel.read(buff);
Complete Read Example: To test the program, create
notes_read.txt
file as below :
Test to read techgeeknext notes.
Filechannel read operation test.
Let's read the file using FinleChannel now.
package com.techgeeknext;
import java.io.*;
import java.nio.ByteBuffer;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;
import java.nio.charset.StandardCharsets;
public class FileChannelRead {
public static void main(String[] args) {
try (RandomAccessFile fileReader = new RandomAccessFile("src/main/resources/notes_read.txt", "r");
FileChannel fileReaderChannel = fileReader.getChannel();
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream()) {
int bufferSize = 1024;
if (bufferSize > fileReaderChannel.size()) {
bufferSize = (int) fileReaderChannel.size();
}
ByteBuffer byteBuffer = ByteBuffer.allocate(bufferSize);
while (fileReaderChannel.read(byteBuffer) > 0) {
byteArrayOutputStream.write(byteBuffer.array(), 0, byteBuffer.position());
System.out.println(byteArrayOutputStream);
byteBuffer.clear();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
OutputTest to read techgeeknext notes.
Filechannel read operation test.
ByteBuffer buff = ByteBuffer.wrap("Notes has been added".getBytes(StandardCharsets.UTF_8));
fileWriterChannel.write(buff);
Write the data from the position given.
ByteBuffer buff = ByteBuffer.wrap("Notes has been added".getBytes(StandardCharsets.UTF_8));
fileWriterChannel.write(buff,8);
Complete Example to write in file
package com.techgeeknext;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.StandardCharsets;
public class FileChannelReadWrite {
public static void main(String[] args) {
final String notesFile = "src/main/resources/notes_read.txt";
try (RandomAccessFile fileWriter = new RandomAccessFile(notesFile, "rw");
FileChannel fileWriterChannel = fileWriter.getChannel();
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream()) {
ByteBuffer byteBuffer = ByteBuffer.wrap("Written to test".getBytes(StandardCharsets.UTF_8));
fileWriterChannel.write(byteBuffer);
RandomAccessFile randomAccessFile = new RandomAccessFile(notesFile, "r");
System.out.println(randomAccessFile.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
}
Input File DataThis is to test techgeeknext notes.
OutputWritten to test techgeeknext notes.
get Current Position
obtain the current position of the FileChannel object by calling the position() method.
long currentPosition = fileChannel.position();
Set Current PositionfileChannel.position(8);
FileChannel of a File
long dataSize = fileChannel.size();
FileChannel TruncatefileChannel.truncate(8);
FileChannel of a File
An operating system may cache file changes for performance reasons, and data may be lost if the system crashes. To force file content and metadata to write to disk continuously we can use the force method.
fileChannel.force(true);
Closing a FileChannel
fileChannel.close();