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 Reading a whole file: readString and readAllLines Reading line by line: Files.lines and BufferedReader Parsing words and numbers: Scanner Reading text from an InputStream Reading from a position: RandomAccessFile Reading bytes with FileChannel and memory mapping Character encoding errors How fast is each approach? Which one to use
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 ) decode as they go and hand you characters or lines.InputStreamReader - Byte-level classes (
,InputStream ,RandomAccessFile ) 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.FileChannel - The
helpers (Java 7 and later) wrap both jobs in one call for the common cases.Files
| Approach | Since | Loads | Best for |
|---|---|---|---|
Files.readString | Java 11 | Whole file | Small files used as one piece of text |
Files.readAllLines | Java 7 | Whole file | Small files you need as a list of lines |
Files.lines | Java 8 | One line at a time | Large files processed with streams |
Files.newBufferedReader | Java 7 | One line at a time | Large files with loop logic, such as stopping early |
BufferedReaderFileReader | Java 1.1 | One line at a time | The same, in code that uses FilePath |
Scanner | Java 5 | Token by token | Parsing words and numbers out of text |
InputStreamReader | Java 1.1 | Streamed | Text that arrives as an InputStream |
RandomAccessFile | Java 1.0 | Bytes from any position | Reading part of a file, such as the end of a log |
FileChannel | Java 1.4 | Bytes from any position | Byte 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.
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:
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.é keeps the text exactly, including the final newline.readString removes the line terminators (readAllLines ,\n or\r\n ) and keeps the empty line as an empty string. The final newline does not create a fifth, empty line.\r- Both methods read the whole file into memory.
fails withreadString for a file larger than about 2 GB, because a JavaOutOfMemoryError cannot be that long; long before that, a big file wastes heap.String
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.
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:
Files.lines: 10 ERROR lines
newBufferedReader: first error "ERROR request 1000" after reading 1000 lines
FileReader + BufferedReader: first line "INFO request 1"
returns a lazyFiles.lines : 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.Stream- The
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 servesBufferedReader from that buffer, so most calls touch no disk at all.readLine has existed since Java 11. Older code often writesnew FileReader(file, charset) , 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.new FileReader(file)
Parsing words and numbers: Scanner
ScannernextIntnextBigDecimal
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:
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"0.45"nextBigDecimalInputMismatchExceptionuseLocale(Locale.ROOT)ScannerBufferedReader
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 InputStreamInputStreamReaderü
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:
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()charüüInputStreamReadernew String(bytes, charset)
Reading from a position: RandomAccessFile
All the approaches above start at the beginning of the file. RandomAccessFileseek
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:
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.
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 ofRandomAccessFile.readLine() (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
Reading bytes with FileChannel and memory mapping
FileChannelRandomAccessFileByteBuffer
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:
first 6 bytes: header
mapped slice: footer: €1
file size 5021 bytes, mapped 5021 bytes
reads at offset 0 without moving the channel's position, so several threads can read different parts of one channel safely.ch.read(buf, 0)- The footer
is 11 characters but 13 bytes, which is why the slice is 13 bytes long."footer: €1\n" needs Java 13 or later.MappedByteBuffer.slice(index, length) - 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,
is simpler and fast. SeeBufferedReaderNIO channels andhandling 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é"é
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:
bytes on disk: 4
Files.readString (UTF-8): MalformedInputException
FileReader: caf[U+FFFD]
with ISO_8859_1: equals "café"? true
missing file: NoSuchFileException
| API | On invalid bytes |
|---|---|
Files.readStringFiles.readAllLines | Throws MalformedInputException |
Files.newBufferedReaderFiles.lines | Throws MalformedInputExceptionUncheckedIOExceptionFiles.lines |
FileReaderInputStreamReaderScanner | Silently 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_1NoSuchFileExceptionFilesFileNotFoundExceptionFileReaderRandomAccessFileIOException
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
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):
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
andFiles.lines are the fastest, and they need almost no memory.BufferedReader is slower because it also keeps 500,000 strings in a list.readAllLines is roughly two to three times slower thanScanner , because it matches every line against a regular expression.BufferedReader 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.RandomAccessFile.readLine
Which one to use
| Situation | Use |
|---|---|
| Small file, needed as one string | Files.readString(path) |
| Small file, needed as lines | Files.readAllLines(path) |
| Large file, filter or count with streams | Files.lines(path) |
| Large file, loop with early exit or state | Files.newBufferedReader(path) |
| Words and numbers to parse | ScanneruseLocale(Locale.ROOT) |
Text from an InputStream | InputStreamReader |
| Part of a large file, from a known position | RandomAccessFile.seekFileChannel.read(buf, position) |
| File in a charset other than UTF-8 | Pass the charset to any of the above |
For the reverse direction, see