Java Reference
In-Depth Information
You need a file of bytes in which to read. This can be any file, though files larger than a
few megabytes in size will take a while to finish running. A suitable choice is the pro-
gram's class file, which contains the bytecode instructions executed by the Java virtual
machine. Create this file by making a copy of
ByteReader.class
and renaming the copy
class.dat
. Don't rename the
ByteReader.class
file or you won't be able to run the
program.
15
Windows users can use MS-DOS in a command-line window to cre-
ate
class.dat
. Go to the folder that contains
ByteReader.class
and
use the following command:
TIP
copy ByteReader.class class.dat
Linux users can type the following at a command line:
cp ByteReader.class class.dat
When you run the program, each byte in
class.dat
is displayed, followed by a count of
the total number of bytes. If you used
ByteReader.class
to create
class.dat
, the last
several lines of output should resemble the following:
12 0 50 0 13 0 56 0 14 0 61 0 16 0 64 0 17 0 67 0 18 0 71 0 19 0
96 0 22 0 99 0 20 0 100 0 21 0 128 0 23 0 28 0 0 0 32 0 6 254 0
14 7 0 29 1 1 252 0 46 1 250 0 2 2 255 0 31 0 1 7 0 30 0 1 7 0 31
28 0 1 0 32 0 0 0 2 0 33 -1
Bytes read: 1047
The number of bytes displayed on each line of output depends on the column width that
text can occupy on your system. The bytes shown depend on the file used to create
class.dat
.
File Output Streams
A file output stream can be created with the
FileOutputStream(
String
)
constructor.
The usage is the same as the
FileInputStream(
String
)
constructor, so you can specify
a path along with a filename.
You have to be careful when specifying the file associated with an output stream. If it's
the same as an existing file, the original will be wiped out when you start writing data to
the stream.
You can create a file output stream that appends data after the end of an existing file with
the
FileOutputStream(
String
,
boolean
)
constructor. The string specifies the file, and
the Boolean argument should equal
true
to append data instead of overwriting existing
data.