Lesson 47 of 50 – Reading Files in Java
94%

Reading Files in Java

Java provides several ways to read data from a text file. We can use classes such as Scanner, FileReader, and BufferedReader to read file contents.

1. Introduction to Reading Files

Reading a file means retrieving the data stored inside it.

For example, suppose message.txt contains:

Hello Java!
Welcome to file handling.

Our Java program can read and display this text on the screen.

2. Reading a File Using Scanner

The Scanner class can read text from a file.

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        try {
            File file = new File("message.txt");
            Scanner reader = new Scanner(file);

            while (reader.hasNextLine()) {
                String line = reader.nextLine();
                System.out.println(line);
            }

            reader.close();

        } catch (FileNotFoundException e) {
            System.out.println("File not found.");
        }
    }
}
Explanation
  • File represents the file to read.
  • Scanner reads data from the file.
  • hasNextLine() checks whether another line exists.
  • nextLine() reads the next line.
  • close() closes the scanner.

3. Reading a File Line by Line

Consider a file named students.txt with this content:

Rahul
Amit
Priya
Neha

Java program:

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        try (Scanner reader =
                 new Scanner(new File("students.txt"))) {

            while (reader.hasNextLine()) {
                System.out.println(reader.nextLine());
            }

        } catch (FileNotFoundException e) {
            System.out.println("Unable to find the file.");
        }
    }
}

Output:

Rahul
Amit
Priya
Neha

The try-with-resources statement closes the scanner automatically.

4. Reading a File Using FileReader

FileReader reads characters from a text file. It is useful when you want to process characters directly.

import java.io.FileReader;
import java.io.IOException;

public class Main {
    public static void main(String[] args) {
        try (FileReader reader =
                 new FileReader("message.txt")) {

            int character;

            while ((character = reader.read()) != -1) {
                System.out.print((char) character);
            }

        } catch (IOException e) {
            System.out.println("Error reading file.");
        }
    }
}

The read() method returns the next character as an integer, or -1 when the end of the file is reached.

5. Reading a File Using BufferedReader

BufferedReader reads text efficiently and provides the convenient readLine() method.

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class Main {
    public static void main(String[] args) {
        try (BufferedReader reader =
                 new BufferedReader(
                     new FileReader("message.txt"))) {

            String line;

            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }

        } catch (IOException e) {
            System.out.println("Error reading file.");
        }
    }
}

Remember: readLine() returns null when no more lines are available.

6. Difference Between Scanner and BufferedReader

Scanner BufferedReader
Easy for beginners. Useful for efficient text reading.
Provides methods such as hasNextLine(). Provides the readLine() method.
Can parse values such as integers and doubles. Reads text as characters or lines.
Can be convenient for simple programs. Often preferred for reading lines efficiently.

7. Reading a File Using the Files Class

Modern Java provides the Files class for convenient file operations. The following example reads an entire small text file into a string.

import java.nio.file.Files;
import java.nio.file.Path;
import java.io.IOException;

public class Main {
    public static void main(String[] args) {
        try {
            String content =
                Files.readString(Path.of("message.txt"));

            System.out.println(content);

        } catch (IOException e) {
            System.out.println("Unable to read file.");
        }
    }
}

Files.readString() is available in Java 11 and later. It is suitable for small files that can fit comfortably in memory.

8. Reading All Lines into a List

You can read all lines of a text file into a List<String> using Files.readAllLines().

import java.nio.file.Files;
import java.nio.file.Path;
import java.io.IOException;
import java.util.List;

public class Main {
    public static void main(String[] args) {
        try {
            List<String> lines =
                Files.readAllLines(Path.of("students.txt"));

            for (String line : lines) {
                System.out.println(line);
            }

        } catch (IOException e) {
            System.out.println("Unable to read file.");
        }
    }
}

This method loads all lines into memory, so avoid it for very large files. Use a buffered or streaming approach instead.

9. Reading Numbers from a Text File

Suppose numbers.txt contains:

10
20
30

We can read each line and convert it to an integer:

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        try (Scanner reader =
                 new Scanner(new File("numbers.txt"))) {

            int total = 0;

            while (reader.hasNextLine()) {
                String line = reader.nextLine().trim();

                if (!line.isEmpty()) {
                    total += Integer.parseInt(line);
                }
            }

            System.out.println("Total = " + total);

        } catch (FileNotFoundException e) {
            System.out.println("File not found.");
        } catch (NumberFormatException e) {
            System.out.println("The file contains invalid numbers.");
        }
    }
}

Output:

Total = 60

Integer.parseInt() converts numeric text into an integer. Invalid numeric text causes a NumberFormatException.

10. Handling File Reading Errors

File reading can fail for several reasons:

  • The file does not exist.
  • The program does not have permission to read the file.
  • The file path is incorrect.
  • The file contains data in an unexpected format.

Use exception handling to manage these problems:

try {
    // File reading code goes here.
} catch (IOException e) {
    System.out.println("An error occurred while reading the file.");
}
Tip: Use try-with-resources for readers so that files are closed automatically, even when an error occurs.

11. Relative and Absolute File Paths

A relative path is resolved from the program's working directory.

File file = new File("message.txt");

An absolute path specifies the full file location.

File file = new File("C:/JavaFiles/message.txt");

The file must exist at the specified location, and the program must have permission to read it.

The working directory may differ between an IDE, terminal, and deployed application. Check the path if Java cannot find your file.

12. Best Practices

  • Use try-with-resources to close readers automatically.
  • Handle IOException and other relevant exceptions.
  • Check that file paths point to the intended location.
  • Use BufferedReader for convenient line-by-line reading.
  • Use Files.readString() for small text files when using Java 11 or later.
  • Avoid loading very large files entirely into memory.
  • Specify an appropriate character encoding when your application requires one.

13. Practice Assignments

  1. Create a file named hello.txt and display its contents.
  2. Read a file using the Scanner class.
  3. Read a file line by line using BufferedReader.
  4. Read a file using FileReader and display each character.
  5. Read three numbers from a file and calculate their sum.
  6. Display a message if the file cannot be found.
  7. Read a small text file using Files.readString().
  8. Count the number of lines in a text file.

🧠 Quick Quiz

1. Which method reads the next line using BufferedReader?




2. What does Scanner.hasNextLine() check?




3. Which class provides Files.readString()?