Java Reference
In-Depth Information
15
// Create an input stream for the file
FileInputStream input =
new
FileInputStream(
"temp.dat"
);
16
17
18
// Read values from the file
19
int
value;
20
while
((value = ) !=
-1
)
21 System.out.print(value +
" "
);
22
23
input stream
input.read()
input
// Close the output stream
input.close();
24
25 }
26 }
1 2 3 4 5 6 7 8 9 10
A
FileOutputStream
is created for the file
temp.dat
in line 6. The
for
loop writes ten
byte values into the file (lines 9-10). Invoking
write(i)
is the same as invoking
write((byte)i)
. Line 13 closes the output stream. Line 16 creates a
FileInputStream
for the file
temp.dat
. Values are read from the file and displayed on the console in lines
19-21. The expression
((value = input.read()) != -1)
(line 20) reads a byte from
input.read()
, assigns it to
value
, and checks whether it is
-1
. The input value of
-1
signifies the end of a file.
The file
temp.dat
created in this example is a binary file. It can be read from a Java pro-
gram but not from a text editor, as shown in Figure 19.8.
end of a file
Binary data
F
IGURE
19.8
A binary file cannot be displayed in text mode.
Tip
When a stream is no longer needed, always close it using the
close()
method. Not
closing streams may cause data corruption in the output file, or other programming
errors.
close stream
Note
The root directory for the file is the classpath directory. For the example in this topic, the
root directory is
c:\book
, so the file
temp.dat
is located at
c:\book
. If you wish to
place
temp.dat
in a specific directory, replace line 6 with
where is the file?
FileOutputStream output =
new
FileOutputStream (
"directory/temp.dat"
);
Note
An instance of
FileInputStream
can be used as an argument to construct a
Scanner
, and an instance of
FileOutputStream
can be used as an argument to
construct a
PrintWriter
. You can create a
PrintWriter
to append text into a
file using
appending to text file