/* DemoFileReader.java 2013-11-22 David G. Klick Demonstrates the use of the File, FileReader, and FileWriter objects. */ import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.Scanner; public class DemoFileReader { public static void main(String[] args) { Scanner kbd = new Scanner(System.in); String source, destination; File sourceFile, destinationFile; System.out.print("This program copies a file"); // get name of source file and check it out System.out.print("Enter name of source file: "); source = kbd.nextLine(); if (source.length() == 0) { System.out.println("Error: No source file name was entered"); System.exit(1); } sourceFile = new File(source); if (!sourceFile.exists()) { System.out.println("Error: Source file does not exist"); System.exit(1); } if (!sourceFile.isFile()) { System.out.println("Error: Source file is not a regular file"); System.exit(1); } if (!sourceFile.canRead()) { System.out.println("Error: Source file is not readable"); System.exit(1); } // get name of destination file and check it out System.out.print("Enter name of destination file: "); destination = kbd.nextLine(); if (destination.length() == 0) { System.out.println("Error: No destination file name was entered"); System.exit(1); } destinationFile = new File(destination); if (destinationFile.exists()) { System.out.println("Error: Destination file already exists"); System.exit(1); } // copy file using FileReader and FileWriter // Note: This try/catch block is not a good example of how // to handle file exceptions, but it will work for this // simple program. For example, an error in reading or // writing would trigger an exception and leave both // files open. The complex code needed to check for // all possibilities has been omitted here. Java 7 has // better features for dealing with this problem - but // this example was made to run on Java 6 if needed. try { FileReader inFile = new FileReader(sourceFile); FileWriter outFile = new FileWriter(destinationFile); int ch; while ((ch = inFile.read()) != -1) outFile.write(ch); inFile.close(); outFile.close(); } catch (FileNotFoundException e1) { System.out.println("Error: Source file not found when starting copy"); } catch (IOException e2) { System.out.println("Error: An I/O error has occurred during the copy"); } } }