Reading Files with Scanner

Using the Familiar Scanner Class for File Input

Module 3 • Lesson 3 of 5

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!"

Key Insight

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!

Reading from Keyboard
Scanner input = new Scanner( System.in ); String name = input.nextLine();
Reading from File
File myFile = new File( "data.txt" ); Scanner input = new Scanner( myFile ); String line = input.nextLine();

2 Creating a Scanner for Files

Here's the basic syntax to read from a file:

import java.io.File; import java.io.FileNotFoundException; import java.util.Scanner; public class ReadFile { public static void main(String[] args) { try { // Step 1: Create File object File myFile = new File("data.txt"); // Step 2: Create Scanner with the File Scanner fileReader = new Scanner(myFile); // Step 3: Read from the file String line = fileReader.nextLine(); System.out.println(line); // Step 4: Close the Scanner fileReader.close(); } catch (FileNotFoundException e) { System.out.println("Error: File not found!"); } } }
FileNotFoundException

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():

📄 students.txt
Ahmed 85
Sara 92
Mohammed 78
Fatima 95
import java.io.File; import java.io.FileNotFoundException; import java.util.Scanner; public class ReadAllLines { public static void main(String[] args) { try { File myFile = new File("students.txt"); Scanner fileReader = new Scanner(myFile); // Read line by line until end of file while (fileReader.hasNextLine()) { String line = fileReader.nextLine(); System.out.println(line); } fileReader.close(); } catch (FileNotFoundException e) { System.out.println("Error: File not found!"); } } }
Output
Ahmed 85 Sara 92 Mohammed 78 Fatima 95

5 Reading Specific Data Types

You can read individual tokens of different types:

📄 scores.txt
Ahmed 85
Sara 92
Mohammed 78
import java.io.File; import java.io.FileNotFoundException; import java.util.Scanner; public class ReadStudentScores { public static void main(String[] args) { try { File myFile = new File("scores.txt"); Scanner fileReader = new Scanner(myFile); while (fileReader.hasNext()) { // Read name (String) String name = fileReader.next(); // Read score (int) int score = fileReader.nextInt(); System.out.println( name + " scored " + score + " points" ); } fileReader.close(); } catch (FileNotFoundException e) { System.out.println("Error: File not found!"); } } }
Output
Ahmed scored 85 points Sara scored 92 points Mohammed scored 78 points

6 Always Close the Scanner!

Why Close?

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!

📂
Open File
📖
Read Data
Close Scanner
// Always remember to close! fileReader.close();
Good Practice

Always close your Scanner in a finally block or use try-with-resources (which automatically closes):

// Try-with-resources: Automatically closes! try (Scanner reader = new Scanner(new File("data.txt"))) { while (reader.hasNextLine()) { System.out.println(reader.nextLine()); } } // Scanner automatically closed here!

7 Complete Example

Let's put it all together with a practical example:

📄 grades.txt
3
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.

import java.io.File; import java.io.FileNotFoundException; import java.util.Scanner; public class GradeCalculator { public static void main(String[] args) { try { File file = new File("grades.txt"); Scanner reader = new Scanner(file); // Read number of students int numStudents = reader.nextInt(); System.out.println( "Processing " + numStudents + " students...\n" ); // Process each student for (int i = 0; i < numStudents; i++) { String name = reader.next(); int test1 = reader.nextInt(); int test2 = reader.nextInt(); int test3 = reader.nextInt(); double average = (test1 + test2 + test3) / 3.0; System.out.println( name + ": Average = " + average ); } reader.close(); } catch (FileNotFoundException e) { System.out.println("Error: grades.txt not found!"); } } }
Output
Processing 3 students... Ahmed: Average = 84.33333333333333 Sara: Average = 91.66666666666667 Mohammed: Average = 80.0

8 Summary

Key Takeaways
  • 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!"