Java Reference
In-Depth Information
Like input/output streams, channels are also AutoCloseable . If you use a try-with-resources statement to
obtain a channel, the channel will be closed automatically, thus avoiding a need for you to call the close() method of the
channel explicitly.
Tip
Listing 9-7 puts all of the above steps together. It reads text from a file named luci1.txt . The file should be in
your current working directory. If the file does not exist, the program prints a message with the full path of where the
file is expected to exist. If you do not have this file, create it and enter the following text in the file, before you run the
program:
STRANGE fits of passion have I known:
And I will dare to tell,
But in the lover's ear alone,
What once to me befell.
You need to pay close attention to the call to the clear() and flip() methods on a buffer. When you call the
read() or write() method of a channel, it performs a relative position read/write on the buffer. Therefore, you must
call the flip() method of the buffer to read data from it after the channel writes data into the buffer.
Listing 9-7. Reading from a File Using a Buffer and a Channel
// FileChannelRead.java
package com.jdojo.nio;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
public class FileChannelRead {
public static void main(String[] args) {
// The input file to read from
File inputFile = new File("luci1.txt");
// Make sure the input file exists
if (!inputFile.exists()) {
System.out.println("The input file " +
inputFile.getAbsolutePath() + " does not exist.");
System.out.println("Aborted the file reading process.");
return;
}
// Obtain channel for luci1.txt file to read from it
try (FileChannel fileChannel
= new FileInputStream(inputFile).getChannel()) {
// Create a buffer
ByteBuffer buffer = ByteBuffer.allocate(1024);
 
Search WWH ::




Custom Search