Java Reference
In-Depth Information
21 System.exit( 2 );
22 }
23
24 // Check if target file exists
25 File targetFile = new File(args[ 1 ]);
26 if (targetFile.exists()) {
27 System.out.println( "Target file " + args[ 1 ]
28 + " already exists" );
29 System.exit( 3 );
30 }
31
32
target file
try (
33
// Create an input stream
34
BufferedInputStream input =
input stream
35
new BufferedInputStream( new FileInputStream(sourceFile));
36
37
// Create an output stream
38
BufferedOutputStream output =
output stream
39
new BufferedOutputStream( new FileOutputStream(targetFile));
40 ) {
41 // Continuously read a byte from input and write it to output
42 int r, numberOfBytesCopied = 0 ;
43 while ((r = input.read()) != -1 ) {
44 output.write(( byte )r);
45 numberOfBytesCopied++;
46 }
47
48 // Display the file size
49 System.out.println(numberOfBytesCopied + " bytes copied" );
50 }
51 }
52 }
read
write
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 34 and 35, and an output stream is created using BufferedOutputStream wrapped
on FileOutputStream in lines 38 and 39.
The expression ((r = input.read()) != -1) (line 43) 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.
17.22
How does the program check if a file already exists?
Check
17.23
How does the program detect the end of the file while reading data?
Point
17.24
How does the program count the number of bytes read from the file?
17.6 Object I/O
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
 
 
 
Search WWH ::




Custom Search