import java.util.Scanner; import java.io.*; /** * This class shows how you can read in from a file using a Scanner object. * * This class also shows how to handle a checked exception. A checked * exception is an exception that you can typically anticipate and/or * recover from. In Java, you are required to handle checked exceptions. * * @author alchambers * @version sp18 */ public class FileIO{ /** * Uses a Scanner to read in from a file. This method throws * any I/O exceptions that occur when reading from the file. * * @param filename The name of the file to be read */ private static void readWithScannerThrows(String filename) throws IOException{ System.out.println("Here are the contents of the file:"); File file = new File(filename); Scanner in = new Scanner(file); String line = ""; while(in.hasNext()){ line = in.nextLine(); // read in a line from file System.out.println(line); // print out the line } in.close(); } /** * Uses a Scanner to read in from a file. This method handles * any I/O exceptiosn that occur when reading from the file. * * @param filename The name of the file to be read */ private static void readWithScannerHandles(String filename){ try{ System.out.println("Here are the contents of the file:"); File file = new File(filename); Scanner in = new Scanner(file); String line = ""; while(in.hasNext()){ line = in.nextLine(); // read in a line from file System.out.println(line); // print out the line } in.close(); } catch(IOException e){ System.err.println(e); } } private static void method2(String filename){ readWithScannerHandles(filename); } private static void method1(String filename){ method2(filename); } public static void main(String[] args) { method1("non existent file"); } }