import java.util.Scanner; import java.io.*; /** Oct 10 * Input Files: * 1. import java.io.* * 2. put "throws IOException" clause in header of method * 3. create a File object that is connected to an input file * on disk * 4. Create a Scanner object connected to the File object * created in Step 3 * 5. Now you can read using all your "next" methods of Scanner * class * 6. When you're finished with a file, close the file */ public class InputFiles { // read ins 3 integers from a file public static void main(String[] args) throws IOException { // Step 3: create a File object File myFile = new File("inputData.txt"); if (!myFile.exists()) { System.out.println("The file inputData.text is not found."); System.exit(0); // this will terminate the pgm } // Step 4: create a Scanner object Scanner fileInput = new Scanner(myFile); // following I do the same thing in 1 line of code: //Scanner fileInput = new Scanner(new File("inputData.txt")); // Step 5: start reading int num1, num2, num3; num1 = fileInput.nextInt(); num2 = fileInput.nextInt(); num3 = fileInput.nextInt(); System.out.println("I read in: " + num1 + " " + num2 + " " + num3); fileInput.close(); //DO THIS AGAIN USING A LOOP fileInput = new Scanner(myFile); while (fileInput.hasNextInt()) { int num = fileInput.nextInt(); System.out.println("next number: " + num); } // try to access num i will get a compiler error "cannot find symbol" // since num is out of scope // num++; fileInput.close(); } }