Java Reference
In-Depth Information
A nod is as good as a wink to a blind horse.
Least said, soonest mended.
There are 10 kinds of people in the world, those that understand
binary
and those
that don't.
You can't make a silk purse out of a sow's ear.
Hindsight is always twenty-twenty.
Existentialism has no future.
Those who are not confused are misinformed.
Better untaught that ill-taught.
8 sayings read.
The similarity to what was written in the previous chapter is uncanny.
How It Works
Because each saying is terminated by a line separator, it's easy to read the file back. The readLine()
method for the BufferedReader object returns either a string, or null when EOF is read. Reading the
file and storing the result happens in the loop expression. The while loop, therefore, continues until you
reach the end of the file. The loop just writes each saying to standard output and increments the count of
the number of lines read. It couldn't be simpler!
READING A FILE USING A CHANNEL
You would use channels for file I/O when high-performance is a primary requirement and when you need
multi-threaded to a file. That doesn't apply in our simple examples but they will show you how you can
work with a channel. You used the static newByteChannel() method from the Files class in the previous
chapter to obtain a FileChannel object that writes a file. If you supply no explicit open option arguments,
the READ option is the default. You can then use the channel to read data from the file into one or more buf-
fers. For example:
Path file = Paths.get("D:/Junk/MyFile.txt");
// Make sure we have a directory...
try(ReadableByteChannel inCh = Files.newByteChannel(file)){
// read the file...
} catch(IOException e) {
e.printStackTrace(System.err);
}
This creates a reference to a FileChannel object in the inCh variable with the file that is specified by the
file argument opened for reading. Of course, there's no harm in explicitly specifying the READ option when
you want to read a file.
File Channel Read Operations
The following three FileChannel read operations read bytes starting at the byte indicated by the current
position in the file:
Search WWH ::




Custom Search