Java Read Files

Learn how to read data from files in Java

📖 Reading Files in Java

Java provides several classes for reading files including Scanner, BufferedReader, and FileReader. You can read text line by line, word by word, or entire files with proper exception handling.


// Read a file using Scanner
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class ReadFile {
    public static void main(String[] args) {
        try {
            File file = new File("data.txt");
            Scanner scanner = new Scanner(file);
            while (scanner.hasNextLine()) {
                System.out.println(scanner.nextLine());
            }
            scanner.close();
        } catch (FileNotFoundException e) {
            System.out.println("File not found: " + e.getMessage());
        }
    }
}
                                    

Output:

Line 1 from file
Line 2 from file
Line 3 from file

File Reading Classes

🔍

Scanner

Easy text parsing and reading

Scanner scanner = new Scanner(file);
📚

FileReader

Character-based file reading

FileReader reader = new FileReader("file.txt");

BufferedReader

Efficient buffered reading

BufferedReader buffer = new BufferedReader(reader);
📄

Files.readAllLines()

Read entire file at once

Files.readAllLines(Paths.get("file.txt"));

🔹 Reading with Scanner

Scanner is the most beginner-friendly way to read files:

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

public class ScannerReading {
    public static void main(String[] args) {
        try {
            File myFile = new File("example.txt");
            Scanner scanner = new Scanner(myFile);
            
            System.out.println("Reading file content:");
            System.out.println("====================");
            
            // Read line by line
            while (scanner.hasNextLine()) {
                String line = scanner.nextLine();
                System.out.println(line);
            }
            
            scanner.close();
            System.out.println("====================");
            System.out.println("File reading completed!");
            
        } catch (FileNotFoundException e) {
            System.out.println("File not found: " + e.getMessage());
        }
    }
}

Output:

Reading file content:
====================
Hello World!
This is line 2.
Java file reading is easy.
====================
File reading completed!

🔹 Reading Word by Word

Use Scanner to read individual words:

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

public class WordReading {
    public static void main(String[] args) {
        try {
            File file = new File("words.txt");
            Scanner scanner = new Scanner(file);
            
            System.out.println("Words in the file:");
            int wordCount = 0;
            
            // Read word by word
            while (scanner.hasNext()) {
                String word = scanner.next();
                wordCount++;
                System.out.println(wordCount + ". " + word);
            }
            
            scanner.close();
            System.out.println("Total words: " + wordCount);
            
        } catch (FileNotFoundException e) {
            System.out.println("File not found: " + e.getMessage());
        }
    }
}

Output:

Words in the file:
1. Java
2. is
3. awesome
4. for
5. beginners
Total words: 5

🔹 Using BufferedReader for Large Files

BufferedReader is more efficient for reading large files:

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

public class BufferedReading {
    public static void main(String[] args) {
        try {
            FileReader fileReader = new FileReader("largefile.txt");
            BufferedReader bufferedReader = new BufferedReader(fileReader);
            
            String line;
            int lineNumber = 1;
            
            System.out.println("Reading file with BufferedReader:");
            
            // Read line by line efficiently
            while ((line = bufferedReader.readLine()) != null) {
                System.out.println("Line " + lineNumber + ": " + line);
                lineNumber++;
            }
            
            bufferedReader.close();
            System.out.println("Buffered reading completed!");
            
        } catch (IOException e) {
            System.out.println("Error reading file: " + e.getMessage());
        }
    }
}

Output:

Reading file with BufferedReader:
Line 1: First line of the file
Line 2: Second line of the file
Line 3: Third line of the file
Buffered reading completed!

🔹 Reading Entire File at Once

Use Files.readAllLines() to read the complete file:

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

public class ReadAllLines {
    public static void main(String[] args) {
        try {
            // Read all lines into a List
            List<String> lines = Files.readAllLines(Paths.get("complete.txt"));
            
            System.out.println("File contains " + lines.size() + " lines:");
            System.out.println("=====================================");
            
            // Print each line with line number
            for (int i = 0; i < lines.size(); i++) {
                System.out.println((i + 1) + ": " + lines.get(i));
            }
            
        } catch (IOException e) {
            System.out.println("Error reading file: " + e.getMessage());
        }
    }
}

Output:

File contains 3 lines:
=====================================
1: Welcome to Java
2: File reading tutorial
3: Happy coding!

🔹 Try-with-Resources for Safe Reading

Automatically close resources using try-with-resources:

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

public class SafeReading {
    public static void main(String[] args) {
        // Try-with-resources automatically closes the reader
        try (BufferedReader reader = new BufferedReader(new FileReader("safe.txt"))) {
            
            String line;
            System.out.println("Safe file reading:");
            
            while ((line = reader.readLine()) != null) {
                System.out.println("→ " + line);
            }
            
            System.out.println("File read safely!");
            
        } catch (IOException e) {
            System.out.println("Error: " + e.getMessage());
        }
        // BufferedReader is automatically closed here
    }
}

Output:

Safe file reading:
→ This is safe file reading
→ Resources are automatically closed
File read safely!

🧠 Test Your Knowledge

Which method reads the next line from a Scanner?