Java Read Files

Reading files in Java can be done using several classes, such as FileReader, BufferedReader, and Files. This guide demonstrates how to read data from files efficiently.

1. Using FileReader and BufferedReader

FileReader is a class for reading character files, and BufferedReader can wrap around it to buffer the input and improve efficiency.

Example: Reading a File Line by Line

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

public class ReadFileExample {
    public static void main(String[] args) {
        try {
            FileReader reader = new FileReader("input.txt");
            BufferedReader bufferedReader = new BufferedReader(reader);

            String line;
            while ((line = bufferedReader.readLine()) != null) {
                System.out.println(line);
            }
            bufferedReader.close();
        } catch (IOException e) {
            System.out.println("An error occurred.");
            e.printStackTrace();
        }
    }
}

2. Using Files.readAllLines()

The Files class provides a method to read all lines of a file into a List<String>.

Example: Reading All Lines into a List

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

public class FilesReadAllLinesExample {
    public static void main(String[] args) {
        Path path = Paths.get("input.txt");
        try {
            List<String> lines = Files.readAllLines(path);
            for (String line : lines) {
                System.out.println(line);
            }
        } catch (IOException e) {
            System.out.println("An error occurred.");
            e.printStackTrace();
        }
    }
}

3. Using Scanner Class

The Scanner class can also be used to read files, especially when you need to parse primitive types and strings using regular expressions.

Example: Reading a File with Scanner

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

public class ScannerFileReadExample {
    public static void main(String[] args) {
        try {
            File file = new File("input.txt");
            Scanner scanner = new Scanner(file);

            while (scanner.hasNextLine()) {
                String line = scanner.nextLine();
                System.out.println(line);
            }
            scanner.close();
        } catch (FileNotFoundException e) {
            System.out.println("An error occurred.");
            e.printStackTrace();
        }
    }
}

4. Key Takeaways

  • Use BufferedReader for efficient reading of text files.
  • Files.readAllLines() is convenient for small files.
  • The Scanner class is useful for parsing formatted input.
  • Always handle exceptions and close resources after use.
  • Be mindful of file encoding and large file sizes when choosing a reading method.