Java Reference
In-Depth Information
new
BufferedInputStream(
new
FileInputStream(sourceFile));
34
35
36
// Create an output stream
37
38
39
40
BufferedOutputStream output =
output stream
new
BufferedOutputStream(
new
FileOutputStream(targetFile));
// Continuously read a byte from input and write it to output
41
int
r, numberOfBytesCopied =
0
;
r = input.read()
read
write
42
while
((
) !=
-1
) {
43
44 numberOfBytesCopied++;
45 }
46
47
// Close streams
48 input.close();
49 output.close();
50
51
// Display the file size
52 System.out.println(numberOfBytesCopied +
" bytes copied"
);
53 }
54 }
output.write((
byte
)r);
close stream
The program first checks whether the user has passed the two required arguments from the
command line in lines 10-14.
The program uses the
File
class to check whether the source file and target file exist. If
the source file does not exist (lines 18-22) or if the target file already exists (lines 25-30), the
program ends.
An input stream is created using
BufferedInputStream
wrapped on
FileInputStream
in lines 33-34, and an output stream is created using
BufferedOutputStream
wrapped on
FileOutputStream
in lines 37-38.
The expression
((r = input.read()) != -1)
(line 42) reads a byte from
input.read()
, assigns it to
r
, and checks whether it is
-1
. The input value of
-1
signifies
the end of a file. The program continuously reads bytes from the input stream and sends them
to the output stream until all of the bytes have been read.
19.22
How does the program check if a file already exists?
19.23
How does the program detect the end of the file while reading data?
19.24
How does the program count the number of bytes read from the file?
✓
✓
Check
Point
ObjectInputStream
/
ObjectOutputStream
classes can be used to read/write
serializable objects.
Key
Point
DataInputStream
/
DataOutputStream
enables you to perform I/O for primitive type val-
ues and strings.
ObjectInputStream
/
ObjectOutputStream
enables you to perform I/O
for objects in addition to primitive type values and strings. Since
ObjectInputStream
/
ObjectOutputStream
contains all the functions of
DataInputStream
/
DataOutputStream
, you can replace
DataInputStream
/
DataOutputStream
com-
pletely with
ObjectInputStream
/
ObjectOutputStream
.
ObjectInputStream
extends
InputStream
and implements
ObjectInput
and
ObjectStreamConstants
, as shown in Figure 19.15.
ObjectInput
is a subinterface of
DataInput
(
DataInput
is shown in Figure 19.9).
ObjectStreamConstants
contains the
constants to support
ObjectInputStream
/
ObjectOutputStream
.
VideoNote
Object I/O