Java Reference
In-Depth Information
File exists
Delete file
Copy
Source
does not
exist
F IGURE 19.14
The program copies a file.
To copy the contents from a source file to a target file, it is appropriate to use an input
stream to read bytes from the source file and an output stream to send bytes to the target file,
regardless of the file's contents. The source file and the target file are specified from the
command line. Create an InputFileStream for the source file and an OutputFileStream
for the target file. Use the read() method to read a byte from the input stream, and then use
the write(b) method to write the byte to the output stream. Use BufferedInputStream
and BufferedOutputStream to improve the performance. Listing 19.4 gives the solution to
the problem.
L ISTING 19.4 Copy.java
1 import java.io.*;
2
3 public class Copy {
4
/** Main method
5
@param args[0] for source file
6
@param args[1] for target file
7 */
8 public static void main(String[] args) throws IOException {
9 // Check command-line parameter usage
10 if (args.length != 2 ) {
11 System.out.println(
12 "Usage: java Copy sourceFile targetFile" );
13 System.exit( 1 );
14 }
15
16
check usage
// Check whether source file exists
File sourceFile = new File(args[ 0 ]);
17
18 if (!sourceFile.exists()) {
19 System.out.println( "Source file " + args[ 0 ]
20 + " does not exist" );
21 System.exit( 2 );
22 }
23
24
source file
// Check whether target file exists
File targetFile = new File(args[ 1 ]);
25
26 if (targetFile.exists()) {
27 System.out.println( "Target file " + args[ 1 ]
28 + " already exists" );
29 System.exit( 3 );
30 }
31
32
target file
// Create an input stream
BufferedInputStream input =
33
input stream
 
 
Search WWH ::




Custom Search