How to read a text file in Java

Java can read a text file in at least nine ways, spread over three generations of APIs. They differ in how much of the file they load, whether they can start at an arbitrary position, and how they turn bytes into characters. This page runs each one, measures them on the same 23 MB file, and shows the encoding mistakes that cause most reading bugs.

Contents

How reading a text file works

A file on disk holds bytes. Text only appears when something decodes those bytes into characters using a charset such as UTF-8. Every way of reading text in Java does two jobs: getting bytes from the file, and decoding them. The approaches differ in where they do each job:

  • Reader classes (BufferedReader, FileReader, InputStreamReader) decode as they go and hand you characters or lines.
  • Byte-level classes (InputStream, RandomAccessFile, FileChannel) hand you bytes, and decoding is your job. That is more work, but they can do things readers cannot, such as jumping to a byte position.
  • The Files helpers (Java 7 and later) wrap both jobs in one call for the common cases.
The ways to read text, and what each is for
ApproachSinceLoadsBest for
Files.readStringJava 11Whole fileSmall files used as one piece of text
Files.readAllLinesJava 7Whole fileSmall files you need as a list of lines
Files.linesJava 8One line at a timeLarge files processed with streams
Files.newBufferedReaderJava 7One line at a timeLarge files with loop logic, such as stopping early
BufferedReader + FileReaderJava 1.1One line at a timeThe same, in code that uses File rather than Path
ScannerJava 5Token by tokenParsing words and numbers out of text
InputStreamReaderJava 1.1StreamedText that arrives as an InputStream: classpath resources, sockets, ZIP entries
RandomAccessFileJava 1.0Bytes from any positionReading part of a file, such as the end of a log
FileChannel and memory mappingJava 1.4Bytes from any positionByte ranges of very large files; shared, positional access

The examples below are complete programs, compiled and run on JDK 21. Each one creates its own temporary file, so you can paste it into a file and run it with java ClassName.java.

Reading a whole file: readString and readAllLines

For a file that easily fits in memory, one call is enough. The test file has four lines with two details worth seeing: the euro sign and the accented letters are not ASCII, so the number of characters differs from the number of bytes, and the third line is empty.

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

public class ReadWholeFile {

    public static void main(String[] args) throws IOException {
        Path file = Files.createTempFile("notes", ".txt");
        // 4 lines: non-ASCII characters (€, é) and an empty third line
        Files.writeString(file, "Coffee €3.50\nCroissant €2.20\n\nCrème brûlée €6.00\n");

        // 1. The whole file as one String (Java 11+)
        String text = Files.readString(file);
        System.out.println("readString: " + text.length() + " chars from "
                + Files.size(file) + " bytes");
        System.out.println("ends with a newline? " + text.endsWith("\n"));

        // 2. The whole file as a list of lines, without line terminators
        List<String> lines = Files.readAllLines(file);
        System.out.println("readAllLines: " + lines.size() + " lines");
        for (int i = 0; i < lines.size(); i++) {
            System.out.println("  [" + i + "] \"" + lines.get(i) + "\"");
        }

        Files.delete(file);
    }
}

Output:

Output
readString: 49 chars from 58 bytes
ends with a newline? true
readAllLines: 4 lines
  [0] "Coffee €3.50"
  [1] "Croissant €2.20"
  [2] ""
  [3] "Crème brûlée €6.00"
  • The file is 58 bytes but 49 characters. In UTF-8, € takes 3 bytes and è, û and é take 2 each: three euro signs add 6 extra bytes and three accented letters add 3.
  • readString keeps the text exactly, including the final newline. readAllLines removes the line terminators (\n, \r\n or \r) and keeps the empty line as an empty string. The final newline does not create a fifth, empty line.
  • Both methods read the whole file into memory. readString fails with OutOfMemoryError for a file larger than about 2 GB, because a Java String cannot be that long; long before that, a big file wastes heap.

Reading line by line: Files.lines and BufferedReader

For large files, read one line at a time so memory stays constant however big the file is. The test file is a 10,000-line log in which every 1,000th line is an error, so the program can show both counting all matches and stopping at the first one.

Java
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.stream.Stream;

public class ReadLineByLine {

    public static void main(String[] args) throws IOException {
        Path log = Files.createTempFile("app", ".log");
        StringBuilder sb = new StringBuilder();
        for (int i = 1; i <= 10000; i++) {
            String level = i % 1000 == 0 ? "ERROR" : "INFO";
            sb.append(level).append(" request ").append(i).append('\n');
        }
        Files.writeString(log, sb);

        // 3. Files.lines: a lazy Stream; try-with-resources closes the file
        try (Stream<String> lines = Files.lines(log)) {
            long errors = lines.filter(l -> l.startsWith("ERROR")).count();
            System.out.println("Files.lines: " + errors + " ERROR lines");
        }

        // 4. BufferedReader from java.nio.file: a loop that can stop early
        try (BufferedReader reader = Files.newBufferedReader(log)) {
            String line;
            int read = 0;
            while ((line = reader.readLine()) != null) {
                read++;
                if (line.startsWith("ERROR")) {
                    System.out.println("newBufferedReader: first error \"" + line
                            + "\" after reading " + read + " lines");
                    break;
                }
            }
        }

        // 5. The classic java.io version: FileReader inside a BufferedReader
        try (BufferedReader reader = new BufferedReader(
                new FileReader(log.toFile(), StandardCharsets.UTF_8))) {
            System.out.println("FileReader + BufferedReader: first line \""
                    + reader.readLine() + "\"");
        }

        Files.delete(log);
    }
}

Output:

Output
Files.lines: 10 ERROR lines
newBufferedReader: first error "ERROR request 1000" after reading 1000 lines
FileReader + BufferedReader: first line "INFO request 1"
  • Files.lines returns a lazy Stream: lines are read as the stream pulls them. The stream holds the file open, so it must be closed, which is why it sits in try-with-resources. Without that, every call leaks a file handle until the garbage collector happens to clean up.
  • The BufferedReader loop stopped after 1,000 lines and never read the other 9,000. A loop also makes it easy to keep state between lines, such as a line counter or the previous line.
  • BufferedReader reads 8,192 characters at a time into memory and serves readLine from that buffer, so most calls touch no disk at all.
  • new FileReader(file, charset) has existed since Java 11. Older code often writes new FileReader(file), which uses the platform default charset: UTF-8 since Java 18 (JEP 400), but before that whatever the operating system used, which is a common reason the same program reads text differently on Windows.

Parsing words and numbers: Scanner

Scanner splits input into tokens, by default at whitespace, and converts them with methods such as nextInt and nextBigDecimal. The test file is a small stock list with a name, a quantity and a price per line.

Java
import java.io.IOException;
import java.math.BigDecimal;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.InputMismatchException;
import java.util.Locale;
import java.util.Scanner;

public class ReadWithScanner {

    public static void main(String[] args) throws IOException {
        Path file = Files.createTempFile("stock", ".txt");
        Files.writeString(file, "apple 12 0.45\npear 7 0.60\nplum 30 0.25\n");

        // 6. Scanner splits text into tokens and converts them to numbers
        BigDecimal total = BigDecimal.ZERO;
        try (Scanner in = new Scanner(file, StandardCharsets.UTF_8)) {
            in.useLocale(Locale.ROOT);                  // "0.45" uses a dot
            while (in.hasNext()) {
                String name = in.next();
                int qty = in.nextInt();
                BigDecimal price = in.nextBigDecimal();
                total = total.add(price.multiply(BigDecimal.valueOf(qty)));
                System.out.printf("%-6s %3d x %s%n", name, qty, price);
            }
        }
        System.out.println("stock value: " + total);

        // Without useLocale, numbers are parsed in the default locale
        try (Scanner in = new Scanner(file, StandardCharsets.UTF_8)) {
            in.useLocale(Locale.GERMANY);               // expects "0,45"
            in.next();
            in.nextInt();
            in.nextBigDecimal();
        } catch (InputMismatchException e) {
            System.out.println("with Locale.GERMANY: InputMismatchException on \"0.45\"");
        }
        Files.delete(file);
    }
}

Output:

Output
apple   12 x 0.45
pear     7 x 0.60
plum    30 x 0.25
stock value: 17.10
with Locale.GERMANY: InputMismatchException on "0.45"

The total is 12 × 0.45 + 7 × 0.60 + 30 × 0.25 = 5.40 + 4.20 + 7.50 = 17.10. The second block shows the trap: Scanner reads numbers using the default locale's format. In a German locale the decimal separator is a comma, so "0.45" is not a number and nextBigDecimal throws InputMismatchException. A program that works on a developer's machine can fail on a server configured for another country, so set useLocale(Locale.ROOT) for machine-written files. Scanner is also noticeably slower than BufferedReader for plain line reading, as the measurements below show; use it when you need its parsing.

Reading text from an InputStream

Text often does not come from a file path at all: a resource inside a JAR, a network socket, an entry in a ZIP file and an HTTP upload all arrive as an InputStream of bytes. InputStreamReader is the bridge from bytes to characters. Here a byte array stands in for any such stream, and the text contains ü, a 2-byte character in UTF-8.

Java
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;

public class ReadFromStream {

    // Stands in for any InputStream: a classpath resource, a socket, a ZIP entry, an upload
    static InputStream open() {
        byte[] utf8 = "line one\nline two: ü\n".getBytes(StandardCharsets.UTF_8);
        return new ByteArrayInputStream(utf8);
    }

    public static void main(String[] args) throws IOException {
        // 7a. InputStreamReader turns bytes into characters with an explicit charset
        try (BufferedReader reader = new BufferedReader(
                new InputStreamReader(open(), StandardCharsets.UTF_8))) {
            System.out.println("readLine: " + reader.readLine());
            System.out.println("readLine: " + reader.readLine());
        }

        // 7b. Small streams: read all bytes, then decode once
        try (InputStream in = open()) {
            String text = new String(in.readAllBytes(), StandardCharsets.UTF_8);
            System.out.println("readAllBytes: " + text.length() + " chars");
        }

        // The mistake: decoding each byte as a char breaks every non-ASCII character
        try (InputStream in = open()) {
            StringBuilder wrong = new StringBuilder();
            int b;
            while ((b = in.read()) != -1) {
                wrong.append((char) b);
            }
            String second = wrong.toString().split("\n")[1];
            System.out.println("byte as char: \"" + second + "\" (" + second.length()
                    + " chars instead of " + "line two: ü".length() + ")");
        }
    }
}

Output:

Output
readLine: line one
readLine: line two: ü
readAllBytes: 21 chars
byte as char: "line two: ü" (12 chars instead of 11)

The last line shows the most common hand-written mistake: reading bytes with InputStream.read() and casting each one to char. That treats every byte as a whole character, so the two bytes of ü become two wrong characters, ü, and the line has 12 characters instead of 11. This garbled form is called mojibake. Always decode bytes with a charset, through InputStreamReader or new String(bytes, charset). For reading resources from the classpath, see classpath resources.

Reading from a position: RandomAccessFile

All the approaches above start at the beginning of the file. RandomAccessFile can seek to any byte position and read from there, which is what you need to read the last lines of a large log, or one record in a file of fixed-size records. The test file is a 100,000-line log of about 1.2 MB whose last line contains a euro sign; the program reads only its last 40 bytes.

Java
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;

public class ReadAtPosition {

    public static void main(String[] args) throws IOException {
        Path log = Files.createTempFile("server", ".log");
        StringBuilder sb = new StringBuilder();
        for (int i = 1; i <= 100000; i++) {
            sb.append("event ").append(i).append(i == 100000 ? " paid €42" : "").append('\n');
        }
        Files.writeString(log, sb);
        System.out.println("file size: " + Files.size(log) + " bytes");

        // 8. RandomAccessFile: jump to a byte position and read only what you need
        try (RandomAccessFile raf = new RandomAccessFile(log.toFile(), "r")) {
            long start = Math.max(0, raf.length() - 40);
            raf.seek(start);                            // the last 40 bytes
            byte[] tail = new byte[(int) (raf.length() - start)];
            raf.readFully(tail);
            String text = new String(tail, StandardCharsets.UTF_8);
            String[] lines = text.split("\n");
            System.out.println("tail, decoded as UTF-8:");
            for (int i = 1; i < lines.length; i++) {    // lines[0] may be cut off
                System.out.println("  " + lines[i]);
            }

            // readLine() is a trap for text: it turns each byte into one char
            raf.seek(start);
            raf.readLine();                             // skip the partial line
            String line;
            String last = null;
            while ((line = raf.readLine()) != null) {
                last = line;
            }
            System.out.println("RandomAccessFile.readLine: \"" + visible(last) + "\"");
        }
        Files.delete(log);
    }

    // Shows invisible control characters such as U+0082 as [U+0082]
    static String visible(String s) {
        StringBuilder out = new StringBuilder();
        for (char c : s.toCharArray()) {
            out.append(Character.isISOControl(c) ? String.format("[U+%04X]", (int) c) : c);
        }
        return out.toString();
    }
}

Output:

Output
file size: 1188906 bytes
tail, decoded as UTF-8:
  event 99999
  event 100000 paid €42
RandomAccessFile.readLine: "event 100000 paid â[U+0082]¬42"
  • Seeking to 40 bytes before the end lands somewhere in the middle of a line, so the first, partial line is dropped. Decoding the bytes with UTF-8 gives the correct text, including €. Out of 1.2 MB, only 40 bytes were read.
  • When cutting at a byte position, the cut can also fall inside a multi-byte character. Here it fell in an ASCII line, so the decoded text is clean; in general, start decoding after the first newline, as this program does.
  • RandomAccessFile.readLine() looks convenient but is wrong for text. Its documentation says it converts each byte into a character on its own, so it does not support Unicode: the 3 bytes of € (0xE2 0x82 0xAC) became three characters, one of them the invisible control character U+0082. It also reads one byte per system call, which makes it very slow, as the next-but-one section shows.

For fixed-size records, writing in place and the file pointer, see the RandomAccessFile page.

Reading bytes with FileChannel and memory mapping

FileChannel is the NIO equivalent of RandomAccessFile: it reads bytes into a ByteBuffer, from the current position or from any offset you pass. It can also map a file into memory, after which reading the file is reading memory, and the operating system loads pages on demand. The test file has a short header, 5,000 filler bytes, and a footer with a euro sign.

Java
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;

public class ReadWithChannel {

    public static void main(String[] args) throws IOException {
        Path file = Files.createTempFile("channel", ".txt");
        Files.writeString(file, "header\n" + "x".repeat(5000) + "\nfooter: €1\n");

        try (FileChannel ch = FileChannel.open(file, StandardOpenOption.READ)) {
            // 9a. Read a byte range into a buffer, from any position
            ByteBuffer buf = ByteBuffer.allocate(6);
            ch.read(buf, 0);                            // positional read, offset 0
            buf.flip();
            System.out.println("first 6 bytes: " + StandardCharsets.UTF_8.decode(buf));

            // 9b. Map the file into memory and decode a slice of it
            MappedByteBuffer map = ch.map(FileChannel.MapMode.READ_ONLY, 0, ch.size());
            int footer = (int) ch.size() - 13;          // "footer: €1\n" is 13 bytes
            CharBuffer text = StandardCharsets.UTF_8.decode(map.slice(footer, 13));
            System.out.println("mapped slice:  " + text.toString().strip());
            System.out.println("file size " + ch.size() + " bytes, mapped "
                    + map.capacity() + " bytes");
        }
        Files.delete(file);
    }
}

Output:

Output
first 6 bytes: header
mapped slice:  footer: €1
file size 5021 bytes, mapped 5021 bytes
  • ch.read(buf, 0) reads at offset 0 without moving the channel's position, so several threads can read different parts of one channel safely.
  • The footer "footer: €1\n" is 11 characters but 13 bytes, which is why the slice is 13 bytes long. MappedByteBuffer.slice(index, length) needs Java 13 or later.
  • Channels work in bytes, so line splitting and decoding are your job. They pay off for very large files and binary formats; for ordinary line reading, BufferedReader is simpler and fast. See NIO channels and handling large files for more.

Character encoding errors

The same bytes mean different text in different charsets, and reading with the wrong one is the most common text-file bug. This program saves "café" in ISO-8859-1, as an older Windows program might. In that charset é is the single byte 0xE9, which is not valid UTF-8 on its own, so reading the file as UTF-8 must fail somehow. The question is how.

Java
import java.io.FileReader;
import java.io.IOException;
import java.nio.charset.MalformedInputException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.NoSuchFileException;
import java.nio.file.Path;

public class CharsetPitfalls {

    public static void main(String[] args) throws IOException {
        Path file = Files.createTempFile("latin1", ".txt");
        // "café" saved by an old program in ISO-8859-1: é is the single byte 0xE9
        Files.writeString(file, "café", StandardCharsets.ISO_8859_1);
        System.out.println("bytes on disk: " + Files.size(file));

        // Files.readString defaults to UTF-8 and refuses invalid input
        try {
            Files.readString(file);
        } catch (MalformedInputException e) {
            System.out.println("Files.readString (UTF-8): MalformedInputException");
        }

        // FileReader defaults to UTF-8 too (Java 18+), but silently substitutes U+FFFD
        try (FileReader reader = new FileReader(file.toFile())) {
            StringBuilder sb = new StringBuilder();
            int c;
            while ((c = reader.read()) != -1) {
                sb.append((char) c);
            }
            System.out.println("FileReader: " + sb.toString().replace("\uFFFD", "[U+FFFD]"));
        }

        // Naming the right charset reads it correctly
        String ok = Files.readString(file, StandardCharsets.ISO_8859_1);
        System.out.println("with ISO_8859_1: equals \"café\"? " + ok.equals("café"));

        Files.delete(file);
        try {
            Files.readString(file);
        } catch (NoSuchFileException e) {
            System.out.println("missing file: NoSuchFileException");
        }
    }
}

Output:

Output
bytes on disk: 4
Files.readString (UTF-8): MalformedInputException
FileReader: caf[U+FFFD]
with ISO_8859_1: equals "café"? true
missing file: NoSuchFileException
What each API does with bytes that are invalid in the charset
APIOn invalid bytes
Files.readString, Files.readAllLinesThrows MalformedInputException
Files.newBufferedReader, Files.linesThrows MalformedInputException (wrapped in UncheckedIOException by Files.lines)
FileReader, InputStreamReader, ScannerSilently replaces them with U+FFFD, the replacement character

Failing is usually better: replaced characters look like a small glitch but can end up stored in a database or sent to customers. The fix is to pass the charset the file was really written in, here StandardCharsets.ISO_8859_1. A missing file gives NoSuchFileException from the Files methods and FileNotFoundException from FileReader and RandomAccessFile; both are subclasses of IOException.

How fast is each approach?

To compare the line-based approaches, the program writes a 500,000-line log of about 23 MB and counts its lines with each one. Each approach runs 3 times and the fastest run is reported, so the first run's JIT compilation and disk caching do not decide the result. This is a rough comparison, not a benchmark; see the JMH page for measuring properly.

Java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Scanner;
import java.util.stream.Stream;

public class ReadSpeed {

    interface Reader {
        long count(Path file) throws IOException;
    }

    public static void main(String[] args) throws IOException {
        Path file = Files.createTempFile("speed", ".txt");
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < 500000; i++) {
            sb.append("2026-11-14T10:15:30 INFO order ").append(i).append(" shipped\n");
        }
        Files.writeString(file, sb);
        System.out.printf("file: 500,000 lines, %.1f MB%n", Files.size(file) / 1e6);

        time("Files.readAllLines", file, f -> Files.readAllLines(f).size());
        time("Files.lines", file, f -> {
            try (Stream<String> s = Files.lines(f)) {
                return s.count();
            }
        });
        time("BufferedReader.readLine", file, f -> {
            long n = 0;
            try (BufferedReader r = Files.newBufferedReader(f)) {
                while (r.readLine() != null) {
                    n++;
                }
            }
            return n;
        });
        time("Scanner.nextLine", file, f -> {
            long n = 0;
            try (Scanner s = new Scanner(f, StandardCharsets.UTF_8)) {
                while (s.hasNextLine()) {
                    s.nextLine();
                    n++;
                }
            }
            return n;
        });
        time("RandomAccessFile.readLine", file, f -> {
            long n = 0;
            try (RandomAccessFile r = new RandomAccessFile(f.toFile(), "r")) {
                while (r.readLine() != null) {
                    n++;
                }
            }
            return n;
        });
        Files.delete(file);
    }

    // Runs each reader 3 times and reports the fastest, so JIT warm-up is not measured
    static void time(String name, Path file, Reader reader) throws IOException {
        long best = Long.MAX_VALUE;
        long lines = 0;
        for (int run = 0; run < 3; run++) {
            long t0 = System.nanoTime();
            lines = reader.count(file);
            best = Math.min(best, System.nanoTime() - t0);
        }
        System.out.printf("%-26s %,8d lines %,8d ms%n", name, lines, best / 1000000);
    }
}

Output (2-CPU Linux machine, JDK 21; absolute times will differ on yours):

Output
file: 500,000 lines, 22.9 MB
Files.readAllLines          500,000 lines       94 ms
Files.lines                 500,000 lines       36 ms
BufferedReader.readLine     500,000 lines       37 ms
Scanner.nextLine            500,000 lines       96 ms
RandomAccessFile.readLine   500,000 lines    5,254 ms
  • Files.lines and BufferedReader are the fastest, and they need almost no memory. readAllLines is slower because it also keeps 500,000 strings in a list.
  • Scanner is roughly two to three times slower than BufferedReader, because it matches every line against a regular expression.
  • RandomAccessFile.readLine is far slower than everything else. It is not buffered and makes a system call for every byte, about 23 million of them here. Never use it to read a file line by line.

Which one to use

Choosing a way to read text
SituationUse
Small file, needed as one stringFiles.readString(path)
Small file, needed as linesFiles.readAllLines(path)
Large file, filter or count with streamsFiles.lines(path) in try-with-resources
Large file, loop with early exit or stateFiles.newBufferedReader(path)
Words and numbers to parseScanner with useLocale(Locale.ROOT)
Text from an InputStreamInputStreamReader with an explicit charset
Part of a large file, from a known positionRandomAccessFile.seek or FileChannel.read(buf, position), then decode the bytes
File in a charset other than UTF-8Pass the charset to any of the above

For the reverse direction, see writing a text file in Java.