Lecture Videos
  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");
 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      try (
 33        // Create an input stream
 34        BufferedInputStream input = 
 35          new BufferedInputStream(new FileInputStream(sourceFile));
 36    
 37        // Create an output stream
 38        BufferedOutputStream output = 
 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  }