Java Reference
In-Depth Information
Random Access to a File
A SeekableByteChannel object provides random access to a file using the channel API. You can use it to read data
from and write data to a file. It is an interface declared in the java.nio.channels package. The FileChannel class
in the java.nio.channels package implements this interface. You can get a SeekableByteChannel object for a Path
using the newByteChannel() method of the Files class as follows:
Path src = Paths.get("twinkle2.txt");
SeekableByteChannel seekableChannel =
Files.newByteChannel(src, READ, WRITE, CREATE, TRUNCATE_EXISTING);
A SeekableByteChannel is connected to an entity such as a file. It maintains a current position. When you
write to the channel, the data is written at the current position. If you read from it, the data is read from the current
position. You can get the current position using its position() method. To set its current position, you need to use its
position(long newPosition) method.
You can get the size of the entity of a SeekableByteChannel in bytes using its size() method. As the data is
truncated or written to the channel, the size is updated.
The truncate(long size) method of the SeekableByteChannel lets you truncate the size of the entity to the
specified size . If the specified size is less than the current size of the entity, it truncates the data to the specified size .
If the specified size is greater than or equal to the current size of the entity, this method does not modify the entity.
Use the read(ByteBuffer source) and write(ByteBuffer destination) methods to read data from the
channel and write data to the channel, respectively. Make sure to set the current position correctly, before you
perform the read and write operations on the channel.
Listing 10-9 shows how to read from and write to a file using a SeekableByteChannel . It creates a file named
twinkle2.txt in the default directory and writes a few lines of text to it. It resets the position to zero after writing the
data and reads the texts to print them on the standard output. At every step, it prints the size and the current position.
Listing 10-9. A Sample Program That Uses a SeekableByteChannel to Read Data from and Write Data to a File
// SeekableByteChannelTest.java
package com.jdojo.nio2;
import java.nio.ByteBuffer;
import java.nio.charset.Charset;
import java.io.IOException;
import java.nio.CharBuffer;
import java.nio.channels.SeekableByteChannel;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.Files;
import static java.nio.file.StandardOpenOption.READ;
import static java.nio.file.StandardOpenOption.WRITE;
import static java.nio.file.StandardOpenOption.CREATE;
import static java.nio.file.StandardOpenOption.TRUNCATE_EXISTING;
public class SeekableByteChannelTest {
public static void main(String[] args) {
Path src = Paths.get("twinkle2.txt");
 
Search WWH ::




Custom Search