Shiklo Programming
EN
  • English
  • Español
  • Português
  • Deutsch
  • Français
  • 日本語
  • हिन्दी

Java Read Files

Reading is the other half of working with files. Depending on the size of the file and what you want to do with it, Java offers several ways: read everything at once, read it as a list of lines, or read one line at a time. Each example below first writes a small file so that it has something to read.

All at once

For small files, Files.readString (the whole text) and Files.readAllLines (a list of lines) are the simplest:

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

public class Main {
    public static void main(String[] args) throws IOException {
        Path poem = Path.of("poem.txt");
        Files.writeString(poem, "Roses are red\nViolets are blue\nJava is fun\n");
        String all = Files.readString(poem);
        System.out.println(all.length() + " characters");
        List<String> lines = Files.readAllLines(poem);
        System.out.println(lines.size() + " lines, the last one: " + lines.get(lines.size() - 1));
    }
}
Output
43 characters
3 lines, the last one: Java is fun

Line by line with BufferedReader

A large file should not be loaded all at once. A BufferedReader reads one line at a time; readLine() returns null at the end of the file. Use try-with-resources so the file is closed:

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

public class Main {
    public static void main(String[] args) throws IOException {
        Path log = Path.of("server.log");
        Files.writeString(log, "INFO start\nERROR disk full\nINFO retry\nERROR timeout\n");
        int errors = 0;
        try (BufferedReader in = Files.newBufferedReader(log)) {
            String line;
            while ((line = in.readLine()) != null) {
                if (line.startsWith("ERROR")) {
                    errors++;
                    System.out.println("Found: " + line.substring(6));
                }
            }
        }
        System.out.println(errors + " errors");
    }
}
Output
Found: disk full
Found: timeout
2 errors

The condition (line = in.readLine()) != null reads a line, stores it and checks it in one step: a common Java idiom.

Reading data with split

Data files often have one record per line with values separated by commas (CSV). Split each line with split from String Methods and convert the parts:

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

public class Main {
    public static void main(String[] args) throws IOException {
        Path csv = Path.of("marks.csv");
        Files.writeString(csv, "name,marks\nAsha,82\nBen,67\nChitra,91\n");
        int total = 0, count = 0;
        for (String line : Files.readAllLines(csv)) {
            if (line.startsWith("name")) {
                continue; // skip the header line
            }
            String[] parts = line.split(",");
            int marks = Integer.parseInt(parts[1]);
            System.out.printf("%-7s %3d%n", parts[0], marks);
            total += marks;
            count++;
        }
        System.out.printf("Average: %.1f%n", (double) total / count);
    }
}
Output
Asha     82
Ben      67
Chitra   91
Average: 80.0

Scanner on a file

The Scanner you used for keyboard input can also read a file, with the same nextInt, next and hasNext methods:

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

public class Main {
    public static void main(String[] args) throws IOException {
        Path nums = Path.of("numbers.txt");
        Files.writeString(nums, "4 8 15\n16 23 42\n");
        int sum = 0;
        try (Scanner sc = new Scanner(nums)) {
            while (sc.hasNextInt()) {
                sum += sc.nextInt();
            }
        }
        System.out.println("Sum: " + sum);
    }
}
Output
Sum: 108

When the file is missing

Reading a file that does not exist throws a NoSuchFileException, a kind of IOException. Catch it to give a friendly message:

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

public class Main {
    public static void main(String[] args) {
        try {
            System.out.println(Files.readString(Path.of("missing.txt")));
        } catch (NoSuchFileException e) {
            System.out.println("No such file: " + e.getMessage());
        } catch (IOException e) {
            System.out.println("Could not read the file.");
        }
    }
}
Output
No such file: missing.txt

Practice exercises

  1. Write a file with five numbers, one per line, and print their sum by reading it back.
  2. Count the words in a text file (split each line on spaces).
  3. Read a CSV of products and prices and print the most expensive product.