/* This program takes two file names from the command line and copies the first text file to the second. It is an example showing how to open, close, read and write text files. */ import java.util.*; import java.io.*; public class Copy { public static void main(String[] args) { Scanner in; BufferedWriter out; // check for valid command line if (args.length != 2) { System.out.println("Usage: java Copy inputfilename outputfilename"); System.exit(1); } // open input and output files in = openInput(args[0]); if (in == null) System.exit(1); out = openOutput(args[1]); if (out == null) System.exit(1); // all file operations must be inside try/catch blocks try { while (in.hasNext()) { String textLine = in.nextLine(); // read a line out.write(textLine); // write the line out.newLine(); } out.close(); // if this is left out some output may not be written } catch (IOException e) { System.out.println("file operation failed"); } } // opens file named s for reading -- returns null if fails private static Scanner openInput(String s) { Scanner in; // all file operations must be inside try/catch blocks try { FileReader fr = new FileReader(s); // open the file /* BufferedReader can be skipped and fr passed to the Scanner constructor. Using a BuffredReader improves efficiency. */ BufferedReader br = new BufferedReader(fr); /* Using a Scanner allows "ordinary" reading from tge file similar to reading from the keyboard. */ in = new Scanner(br); } catch (IOException e) { System.out.println("Unable to open " + s); return null; } return in; } // opens file named s for wtiting -- returns null if fails private static BufferedWriter openOutput(String s) { BufferedWriter out; // all file operations must be inside try/catch blocks try { FileWriter fw = new FileWriter(s); //open the file /* BufferedWriter can be skipped. Using a BuffredWriter improves efficiency. */ out = new BufferedWriter(fw); } catch (IOException e) { System.out.println("Unable to open " + s); return null; } return out; } }