1 Scanner: Your Old Friend
The teacher held up the Scanner and said, "You've used Scanner before to read input from the keyboard. Now, you can hand the File object to Scanner, and it will read text from that file instead!"
We've used Scanner before with System.in to read from the keyboard. Now, we'll use the same Scanner but give it a File object instead!
2 Creating a Scanner for Files
Here's the basic syntax to read from a file:
When creating a Scanner with a File, Java requires us to handle the possibility that the file doesn't exist. We use try-catch to handle this.
3 Scanner Reading Methods
The same methods you used for keyboard input work for file input:
| Method | Returns | Description |
|---|---|---|
next() |
String | Reads the next word (token, stops at whitespace) |
nextLine() |
String | Reads the entire line (until newline) |
nextInt() |
int | Reads the next integer |
nextDouble() |
double | Reads the next decimal number |
nextBoolean() |
boolean | Reads true or false |
hasNext() |
boolean | Returns true if there's more data |
hasNextLine() |
boolean | Returns true if there's another line |
hasNextInt() |
boolean | Returns true if next token is an integer |
4 Reading an Entire File
To read all lines in a file, use a while loop with hasNextLine():
Sara 92
Mohammed 78
Fatima 95
5 Reading Specific Data Types
You can read individual tokens of different types:
Sara 92
Mohammed 78
6 Always Close the Scanner!
When you open a file for reading, the operating system allocates resources. If you don't close the Scanner, these resources remain locked and can cause problems - especially if you try to modify the file later!
Always close your Scanner in a finally block or use try-with-resources (which automatically closes):
7 Complete Example
Let's put it all together with a practical example:
Ahmed 85 90 78
Sara 92 88 95
Mohammed 78 82 80
The first line tells us there are 3 students. Each following line has a name and 3 test scores.
8 Summary
- ✓ Scanner can read from files the same way it reads from keyboard.
- ✓ Pass a File object to Scanner instead of System.in.
- ✓ Use hasNextLine() or hasNext() to check for more data.
- ✓ Use next(), nextLine(), nextInt(), nextDouble() to read data.
- ✓ Always close() the Scanner when done reading!
- ✓ Handle FileNotFoundException with try-catch.
The student exclaimed, "Reading is easy! But how do I save data to a file?"
The teacher replied, "That's where PrintWriter comes in - let's learn about writing files next!"