Skip to lesson

Read a small text file

A text file is a file of characters arranged in lines, such as a class list, a marks sheet or a settings file. For small text files, Java's Files class reads everything in one call: as one String or as a list of lines.

Files.readString

Files.readString(path) reads a whole text file and returns it as one String. It opens the file, reads it, and closes it again for you.

Example 1 · Files.readString: the whole file as one String

ReadNoticeDemo.javaJava
import java.io.IOException;import java.nio.file.Files;import java.nio.file.Path;
public class ReadNoticeDemo {    public static void main(String[] args) throws IOException {        Path notice = Path.of("notice.txt");        // Create a sample file for the demo (writing files is the next lesson)        Files.writeString(notice, "Fest on 14 Feb.\nVenue: Main Hall.\n");
        String text = Files.readString(notice);        System.out.print(text);        System.out.println("Characters: " + text.length());        System.out.println("Ends with a line break: " + text.endsWith("\n"));
        Files.delete(notice);    }}
Output
Fest on 14 Feb.
Venue: Main Hall.
Characters: 34
Ends with a line break: true

What this code does

  • Files.readString(notice) opens the file, reads every character, closes it and hands back one String.
  • The line breaks stay inside the String: 15 + 1 characters for the first line and 17 + 1 for the second make 34. That is why print, not println, shows it neatly.

The line breaks stay inside the String as \n characters. Use it when you need the text as a whole: to print it, search it with contains, or count its characters. It was added in Java 11.

Files.readAllLines

Files.readAllLines(path) reads a whole text file and returns a List<String>, one item per line. The line break at the end of each line is removed.

Example 2 · Files.readAllLines: one list item per line

MarksListDemo.javaJava
import java.io.IOException;import java.nio.file.Files;import java.nio.file.Path;import java.util.List;
public class MarksListDemo {    public static void main(String[] args) throws IOException {        Path file = Path.of("marks.txt");        Files.writeString(file, "Asha 86\nRavi 72\nMeena 91\n");
        List<String> lines = Files.readAllLines(file);        System.out.println("Lines: " + lines.size());        System.out.println("First: " + lines.get(0));
        int total = 0;        for (String line : lines) {            String[] parts = line.split(" ");            total += Integer.parseInt(parts[1]);        }        System.out.println("Total: " + total);        System.out.println("Average: " + total / lines.size());
        Files.delete(file);    }}
Output
Lines: 3
First: Asha 86
Total: 249
Average: 83

What this code does

  • Each item of the list is one line with its line break removed, so parts[1] is a clean "86" that Integer.parseInt accepts.
  • The line break after Meena 91 ends the last line; it does not add an empty fourth item. The list has exactly 3 lines.

This is the easiest way to process a small file line by line: loop over the list, split each line and parse its parts. An empty file gives an empty list.

The whole file sits in memory

Both methods load the entire file into memory before they return. A class list of 60 names is a few hundred bytes, which costs nothing. A server log of 4 GB does not fit into a normal Java heap, and the program fails with OutOfMemoryError.

Example 3 · Refuse files that are too big to read at once

SizeCheckDemo.javaJava
import java.io.IOException;import java.nio.file.Files;import java.nio.file.Path;
public class SizeCheckDemo {    static final long MAX_BYTES = 1_000_000; // 1 MB is plenty for a class list
    static String readSmall(Path file) throws IOException {        long size = Files.size(file);        if (size > MAX_BYTES) {            throw new IOException(file.getFileName() + " is too big to read at once: " + size + " bytes");        }        return Files.readString(file);    }
    public static void main(String[] args) throws IOException {        Path small = Path.of("classlist.txt");        Path big = Path.of("biglog.txt");        Files.writeString(small, "Asha\nRavi\nMeena\n");        Files.writeString(big, "INFO ok\n".repeat(200_000));
        System.out.println("classlist.txt: " + Files.size(small) + " bytes");        System.out.print(readSmall(small));        try {            readSmall(big);        } catch (IOException e) {            System.out.println("Refused: " + e.getMessage());        }
        Files.delete(small);        Files.delete(big);    }}
Output
classlist.txt: 16 bytes
Asha
Ravi
Meena
Refused: biglog.txt is too big to read at once: 1600000 bytes

What this code does

  • Files.size asks the operating system for the size without reading the file, so the check itself is cheap.
  • The 16-byte class list is read; the 1.6 MB log is refused before any of it is loaded into memory. Pick a limit that fits your program.

A simple rule: use these two methods for files you know are small, such as settings, a class list or one day's attendance. When a file can be large, check Files.size(path) first, or read it line by line.

Reading huge files line by line with Files.lines and BufferedReader comes later in this module.

NoSuchFileException and its message

NoSuchFileException is the exception the Files methods throw when the file does not exist. It is a subclass of IOException, so throws IOException covers it, but you can also catch it on its own to show a clear message.

Example 4 · NoSuchFileException: a friendly message for a missing file

MissingFileDemo.javaJava
import java.io.IOException;import java.nio.file.Files;import java.nio.file.NoSuchFileException;import java.nio.file.Path;import java.util.List;
public class MissingFileDemo {    static List<String> loadRollList(Path file) {        try {            return Files.readAllLines(file);        } catch (NoSuchFileException e) {            System.out.println("File not found: " + e.getMessage());            return List.of();        } catch (IOException e) {            System.out.println("Could not read " + file + ": " + e);            return List.of();        }    }
    public static void main(String[] args) throws IOException {        Path real = Path.of("roll-list.txt");        Files.writeString(real, "101\n102\n");
        List<String> rolls = loadRollList(real);        System.out.println("Rolls loaded: " + rolls.size());
        List<String> typo = loadRollList(Path.of("rolllist.txt"));        System.out.println("Rolls loaded: " + typo.size());
        Files.delete(real);    }}
Output
Rolls loaded: 2
File not found: rolllist.txt
Rolls loaded: 0

What this code does

  • The second call has a typo in the name (no hyphen). readAllLines throws NoSuchFileException, and its message is just the path as you wrote it: rolllist.txt.
  • The specific NoSuchFileException is caught first; the general IOException below it handles every other read problem, such as a file you are not allowed to open.

Its message is the path exactly as you wrote it. For Path.of("rolllist.txt") the message is rolllist.txt, a relative name. The usual causes are a typo in the name or a different working directory, for example running from the IDE instead of the terminal.

Catch NoSuchFileException before IOException; the other order does not compile. Print path.toAbsolutePath() when you are not sure where Java is looking.

Fix the error

Fix the compile errors

Read the error from the Java compiler, then pick the line that makes the file compile.

Round 1 of 2

A method that loads a roll list.

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
public class RollList {
static String load() { return Files.readString(Path.of("rolllist.txt")); }
}

Error

RollList.java:6: error: unreported exception IOException; must be caught or declared to be thrown
    static String load() { return Files.readString(Path.of("rolllist.txt")); }
                                                  ^

Next step

Check your understanding

10 quick questions