Concept
How can a Scanner read input from a file?
ComputerScienceOne / File Input
"Java provides several different classes and utilities that support manipulating and processing files. In general, most file operations may result in an IOException, a checked exception that must be caught and handled. Though there are several ways that you can do file input, the easiest is to use the familiar Scanner class. We’ve previously used this class to read from the standard input, System.in, but it can also be used to read from a file using the File class in the java.io package. The File class is just a representation of a file resource and does not represent the actual file; it cannot be opened and closed. To initialize a Scanner to read from a file you can use the following:\n\nScanner s = null;\n\ntry {\n\ns = new Scanner(new File(\"/user/apps/data.txt\"));\n\n} catch (FileNotFoundException e) {\n\n//handle the exception here\n\n}\n\nWhen initializing a Scanner to read from a file, the exception FileNotFoundException must be caught and handled as it is a checked exception. Otherwise, once created, the Scanner class does not throw any checked exceptions. Once created, you can use the usual methods and functionality provided by the Scanner class, including reading the nextInt(), nextDouble(), next string using next(), or even the entire nextLine(). This last one can be used in conjunction with hasNext() to read an entire file, line-by-line:\n\nString line;\n\nwhile(s.hasNext()) {\n\nline = s.nextLine();\n\n//process the line\n\n}\n\nOnce we are done reading the file, we can close the Scanner to free up resources: s.close()."
Related Ideas
- What is a checked exception in Java?ComputerScienceOne · Checked Exceptions
- How do you read numeric input from a user in Java with Scanner?ComputerScienceOne · Converting Units
- When should you use specialized classes for binary file input?ComputerScienceOne · File Input
- How are files read, written, and properly managed?ComputerScienceOne · Paths
- What types of errors can occur when processing files?ComputerScienceOne · Error Handling
- How do buffered and unbuffered file input/output differ?ComputerScienceOne · Buffered and Unbuffered
- How can you write formatted text to a file with PrintWriter?ComputerScienceOne · File Output
- How do fprintf() and fscanf() read from and write to plaintext files?ComputerScienceOne · Plaintext Files