Java Reference
In-Depth Information
15
// Create an input stream for the file
16 FileInputStream input =
new
FileInputStream(
"temp.dat"
);
17 ) {
18
// Read values from the file
19
int
value;
20
while
((value = input.read()) !=
-1
)
21 System.out.print(value +
" "
);
22 }
23 }
24 }
input stream
input
1 2 3 4 5 6 7 8 9 10
The program uses the try-with-resources to declare and create input and output streams
so that they will be automatically closed after they are used. The
java.io.InputStream
and
java.io.OutputStream
classes implement the
AutoClosable
interface. The
AutoClosable
interface defines the
close()
method that closes a resource. Any object of
the
AutoClosable
type can be used with the try-with-resources syntax for automatic closing.
A
FileOutputStream
is created for the file
temp.dat
in line 7. The
for
loop writes
ten byte values into the file (lines 10-11). Invoking
write(i)
is the same as invoking
write((byte)i)
. 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Ā 17.8.
AutoClosable
end of a file
Binary data
F
IGURE
17.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 or
automatically close it using a try-with-resource statement. 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
Search WWH ::
Custom Search