Java Reference
In-Depth Information
// Open file in a read-only mode
RandomAccessFile raf1 = new RandomAccessFile("luci1.txt", "r");
FileChannel rafReadOnly = raf1.getChannel(); // A read-only channel
// Open file in a read-write mode
RandomAccessFile raf2 = new RandomAccessFile("luci1.txt", "rw");
FileChannel rafReadWrite = raf2.getChannel(); // A read-write channel■
Starting from Java 7, you can obtain a FileChannel using the FileChannel.open() static method. this avoids
the need to create an input/output stream to create a FileChannel . the new open() method uses a Path object, which
is part of NIO 2. please refer to Chapter 9 on NIO 2 for more details on using a Path object.
Tip
Reading/Writing Files
I have covered the basic concepts of buffers and channels. A FileChannel object maintains a position variable as a
buffer does. The read() and write() methods for FileChannel come in two varieties: relative position read/write
and absolute position read/write. The meanings of relative and absolute position read/write are the same as in the
context of a buffer read/write. When you open a FileChannel , its position is set to 0, which is the beginning of the
file. When you read from a FileChannel using a relative read() method, its position is incremented by the number of
bytes read. An absolute position read from a FileChannel does not affect its position. You can get the current value of
the position of a FileChannel object using its position() method. You can set its position to a new position using its
position(int newPosition) method. You need to follow a few easy steps to read data from a file and to write data to
a file using NIO.
The steps to read data from a file using buffer and channel are as follows:
FileInputStream .
Create an object of
FileChannel object using the getChannel() method of FileInputStream .
Get a
ByteBuffer object to read data from the file.
Create a
read() method of the FileChannel object by passing the ByteBuffer object. Make
sure that before you pass the byte buffer, the buffer's position and limit are set appropriately.
A simple rule of thumb is to always call the clear() method on the byte buffer before passing
it to a channel to read data into it. The read() method of a channel returns the number of
bytes read into the buffer.
Call the
flip() method of the buffer, so you can read data into your Java program from the
buffer. The previous step will change the position of the buffer because the channel reads
data into it. You may need to use a CharsetDecoder object to decode the byte buffer into a
character buffer if the bytes you have read represent characters.
Call the
Read data from the buffer into your Java program.
FileChannel into the buffer by calling its read()
method until the read() method returns 0 or -1.
Repeat the process of reading data from the
close() method.
Close the channel using its
 
 
Search WWH ::




Custom Search