Java Reference
In-Depth Information
Chapter 7
Input/Output
In this chapter, you will learn
•
What input/output is in Java
File
object that represents an abstract pathname for a file or a directory in
•
How to work with a
a file system
•
The decorator pattern
•
Byte-based and character-based input/output streams
•
Reading data from a file and writing data to a file
•
Reading and writing primitive type and reference type data to input/output streams
•
Object serialization and deserialization
•
How to develop custom input/output stream classes
Console
and
Scanner
classes to interact with the console
•
The
StringTokenizer
and
StreamTokenizer
classes to split text into tokens based on
delimiters
•
The
What Is Input/Output?
Input/output (I/O) deals with reading data from a source and writing data to a destination. Data is read from the
input source (or simply input) and written to the output destination (or simply output). For example, your keyboard
works as a standard input, letting you read data entered using the keyboard into your program. You have been using
the
System.out.println()
method to print text on the standard output from the very first Java program without your
knowledge that you have been performing I/O.
Typically, you read data stored in a file or you write data to a file using I/O. However, your input and output are
not limited to only files. You may read data from a
String
object and write it to another
String
object. In this case,
the input is a
String
object; the output is also a
String
object. You may read data from a file and write it to a
String
object, which will use a file as an input and a
String
object as an output. Many combinations for input and output are
possible. Input and output do not have to be used together all the time. You may use only input in your program, such
as reading the contents of a file into a Java program. You may use only output in your program, such as writing the
result of a computation to a file.
The
java.io
and
java.nio
(
nio
stands for New I/O) packages contain Java classes that deal with I/O. The
java.io
package has an overwhelming number of classes to perform I/O. It makes learning Java I/O a little complex. The
situation where the number of classes increases to an unmanageable extent is called a
class explosion
and the
java.io
package is a good example of that. It is no wonder that there are some topics in the market that deal only with Java