Java Reference
In-Depth Information
The following program creates a simple disk-to-screen utility that reads a text file called
"test.txt" and displays its contents on the screen. Thus, it is the complement of the key-to-
disk utility shown in the previous section.
In this example, notice that the
FileReader
is wrapped in a
BufferedReader
. This gives
it access to
readLine( )
. Also, closing the
BufferedReader
,
br
in this case, automatically
closes the file.
Ask the Expert
Q
:
I have heard about another I/O package called NIO. Can you tell me about it?
A
:
Originally called
New I/O
, NIO was added to Java by JDK 1.4. It supports a channel-
based approach to I/O operations. The NIO classes are contained in
java.nio
and its
subordinate packages, such as
java.nio.channels
and
java.nio.charset
.
NIO is built on two foundational items:
buffers
and
channels
. A buffer holds data. A
channel represents an open connection to an I/O device, such as a file or a socket. In gen-
eral, to use the new I/O system, you obtain a channel to an I/O device and a buffer to hold
data. You then operate on the buffer, inputting or outputting data as needed.