import java.util.Scanner; import java.io.File; /** * Demonstrates how to create File objects, and use them to * read the contents from files on the disk. */ public class FileInput { /** * Reads the first line from the specified file and prints it, * if the file exists. Tells the user the file doesn't exist * if it's not there. * * The "throws" part is basically a warning label to users of * this method. It tells them that this code might crash if we * try to read from a file that doesn't exist. It won't compile * without the label! */ public void peekAtFile(String filename) throws java.io.FileNotFoundException { File theFile = new File(filename); if (theFile.exists()) { Scanner scan = new Scanner(theFile); String firstLine = scan.nextLine(); System.out.println("First line is: "+firstLine); } else { System.out.println(filename+" doesn't exist!"); } } /** * Any method that calls one with a "throws" warning label ALSO * needs a warning label. */ public void peekAtInputJava() throws java.io.FileNotFoundException { peekAtFile("Input.java"); } /** * This version doesn't just print the first line -- it keeps * reading and printing until it has displayed ALL lines from * the file. */ public void printAllLines(String filename) throws java.io.FileNotFoundException { File theFile = new File(filename); if (theFile.exists()) { Scanner scan = new Scanner(theFile); while(scan.hasNext()) { String line = scan.nextLine(); System.out.println(line); } System.out.println("Done reading from the file."); } else { System.out.println(filename+" doesn't exist!"); } } /** * Similar to printAllLines, except we want to read all of the * integers from a file, add them up, and return the sum. It will * stop if it encounters non-integer stuff in the file. */ public int addUpIntegers(String filename) throws java.io.FileNotFoundException { int sum = 0; File theFile = new File(filename); if (theFile.exists()) { Scanner scan = new Scanner(theFile); while(scan.hasNextInt()) { int num = scan.nextInt(); sum = sum + num; } } else { System.out.println(filename+" doesn't exist!"); } return sum; // For now... } /** * Similar to addUpIntegers, except it skips over any non-integer stuff * it encounters. */ public int addUpIgnoreText(String filename) throws java.io.FileNotFoundException { int sum = 0; File theFile = new File(filename); if (theFile.exists()) { Scanner scan = new Scanner(theFile); while(scan.hasNext()) { if (scan.hasNextInt()) { int num = scan.nextInt(); sum = sum + num; } else { String garbage = scan.next(); // Read the next "word" and discard it } } } else { System.out.println(filename+" doesn't exist!"); } return sum; // For now... } }