Introduction to Java Programming-Comprehensive Version (6th Edition)

 

[Page 615 ( continued )]

18.5. Case Study: Copying File

This case study develops a program that copies files. The user needs to provide a source file and a target file as command-line arguments using the following command:

java Copy source target

The program copies a source file to a target file and displays the number of bytes in the file. If the source does not exist, tell the user that the file has not been found. If the target file already exists, tell the user that the file exists. A sample run of the program is shown in Figure 18.13.

Figure 18.13. The program copies a file.

To copy the contents from a source to a target file, it is appropriate to use a binary input stream to read bytes from the source file and a binary output stream to send bytes to the target file, regardless of the contents of the file. 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 18.3 gives the solution to the problem.

Listing 18.3. Copy.java

(This item is displayed on pages 615 - 616 in the print version)

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 ) {


[Page 616]

11 System.out.println( 12 "Usage: java CopyFile sourceFile targetfile.dat" ); 13 System.exit( ); 14 } 15 16 // Check if source file exists 17 File sourceFile = new File(args[ ]); 18 if (!sourceFile.exists()) { 19 System.out.println( "Source file " + args[ ] + " not exist" ); 20 System.exit( ); 21 } 22 23 // Check if target file exists 24 File targetFile = new File(args[ 1 ]); 25 if (targetFile.exists()) { 26 System.out.println( "Target file " + args[ 1 ] + " already exists" ); 27 System.exit( ); 28 } 29 30 // Create an input stream 31 BufferedInputStream input = 32 new BufferedInputStream( new FileInputStream(sourceFile)); 33 34 // Create an output stream 35 BufferedOutputStream output = 36 new BufferedOutputStream( new FileOutputStream(targetFile)); 37 38 // Display the file size 39 System.out.println( "The file " + args[ ] + " has " + 40 input.available() + " bytes" ); 41 42 // Continuously read a byte from input and write it to output 43 int r; 44 while (( r = input.read() ) != - 1 ) 45 output.write(( byte )r); 46 47 // Close streams 48 input.close(); 49 output.close(); 50 51 System.out.println( "Copy done!" ); 52 } 53 }

 

Категории