Java Reference
In-Depth Information
17.5 Case Study: Copying Files
This section develops a useful utility for copying files.
Key
Point
In this section, you will learn how to write a program that lets users copy files. The user needs
to provide a source file and a target file as command-line arguments using the command:
java Copy source target
VideoNote
Copy file
The program copies the source file to the target file and displays the number of bytes in the
file. The program should alert the user if the source file does not exist or if the target file
already exists. A sample run of the program is shown in FigureĀ 17.15.
File exists
Delete file
Copy
Source
does not
exist
F IGURE 17.15
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 com-
mand 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 17.4 gives the solution to the
problem.
L ISTING 17.4
Copy.java
1 import java.io.*;
2
3 public class Copy {
4 /** Main method
5 @param args[0] for sourcefile
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 if source file exists
17 File sourceFile = new File(args[ 0 ]);
18 if (!sourceFile.exists()) {
19 System.out.println( "Source file " + args[ 0 ]
20 + " does not exist" );
check usage
source file
 
 
 
Search WWH ::




Custom Search