Java Reference
In-Depth Information
public static void consumeData(PipedInputStream pis) {
try {
int num = -1;
while ((num = pis.read()) != -1) {
System.out.println("Reading: " + num);
}
pis.close();
}
catch (Exception e) {
e.printStackTrace();
}
}
}
Writing: 1
Reading: 1
...
Writing: 50
Reading: 50
Reading and Writing Primitive Data Types
An object of the
DataInputStream
class is used to read Java primitive data type values in a machine-independent way
from an input stream. An object of the
DataOutputStream
class is used to write Java primitive data type values in a
machine-independent way to an output stream.
The
DataInputStream
class contains
readXxx()
methods to read a value of data type
Xxx
, where
Xxx
is a Java
primitive data type such as
int
,
char
, etc. For example, to read an
int
value, it contains a
readInt()
method; to read a
char
value, it has a
readChar()
method, etc. It also supports reading strings using the
readUTF()
method.
The
DataOutputStream
class contains a
writeXxx(Xxx value)
method corresponding to each the
readXxx()
method of the
DataInputStream
class, where
Xxx
is a Java primitive data type. It supports writing a string to an output
stream using the
writeUTF(String text)
method. Note that these classes are concrete decorators, which provide
you a convenient way to read and write Java primitive data type values and strings using input and output streams,
respectively. You must have an underlying concrete component linked to a data source or a data sink to use these
classes. For example, to write Java primitive data type values to a file named
primitives.dat
, you construct an object
of
DataOutputStream
as follows:
DataOutputStream dos = new DataOutputStream(new FileOutputStream("primitives.dat"));
Listing 7-21 writes an
int
value, a
double
value, a
boolean
value, and a string to a file named
primitives.dat
.
The file path in the output may be different when you run this program. Listing 7-22 reads those values back. Note that
you must read the values using
DataInputStream
in the same order they were written using
DataOutputStream
. You
need to run the
WritingPrimitives
class before you run the
ReadingPrimitives
class.