How to Read a File in Java: 6 Ways with Examples
Reading a file is one of the first real tasks every Java developer meets: loading settings, importing data or processing logs. Java offers several ways to do it, and choosing the right one depends on the file's size and on what you want to do with its content.
This tutorial shows every common way to read a file in Java 25, each with a complete, tested example.
1. What Is Reading a File in Java?
Reading a file means opening it, transferring its bytes into the program and, for text, decoding those bytes into characters with a charset. Modern Java code uses the Files class for most reads; the classic java.io readers and streams remain useful for large or special cases.
2. Ways to Read a File at a Glance
| Way | Returns | Best for | Since |
|---|---|---|---|
Files.readString() | String | Small text files | Java 11 |
Files.readAllLines() | List<String> | Small files, line by line | Java 7 (UTF-8 overload Java 8) |
Files.lines() | Stream<String> | Large files with filtering | Java 8 |
BufferedReader | One line at a time | Large files, full control | Java 1.1 |
Scanner | Words and numbers | Parsing typed values | Java 5 |
Files.readAllBytes() / InputStream | byte[] | Binary files | Java 7 / 1.0 |
3. Using Files.readString()
The shortest way to read a small text file is a single call that returns the whole content as a String.
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
public class ReadWithReadString {
public static void main(String[] args) throws IOException {
Path note = Files.createTempFile("note", ".txt");
Files.writeString(note, "Meeting moved to 3 PM.\nBring the sales report.\n");
String text = Files.readString(note); // Java 11: whole file, UTF-8
System.out.print(text);
System.out.println("Characters: " + text.length());
Files.delete(note);
}
}
Meeting moved to 3 PM. Bring the sales report. Characters: 47
How it works
Files.readString()(Java 11) reads the file and decodes it as UTF-8.- The returned text includes the line breaks, so it can be printed as it is.
- Use it only for files that comfortably fit in memory.
4. Using Files.readAllLines()
When you need the lines separately, readAllLines() returns them as a list.
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
public class ReadWithReadAllLines {
public static void main(String[] args) throws IOException {
Path guests = Files.createTempFile("guests", ".txt");
Files.writeString(guests, "Anita\nBharat\nChetan\n");
List<String> names = Files.readAllLines(guests); // every line in a List
System.out.println("Guests: " + names.size());
System.out.println("First: " + names.getFirst() + ", last: " + names.getLast()); // Java 21
Files.delete(guests);
}
}
Guests: 3 First: Anita, last: Chetan
How it works
Files.readAllLines()returns aList<String>, one element per line, without line terminators.getFirst()andgetLast()(Java 21) read the ends of the list.
5. Using Files.lines()
For large files, Files.lines() returns a stream that reads lines only as they are needed.
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.stream.Stream;
public class ReadWithLinesStream {
public static void main(String[] args) throws IOException {
Path log = Files.createTempFile("app", ".log");
Files.writeString(log, "INFO started\nWARN slow query\nINFO request ok\nWARN disk 85%\n");
try (Stream<String> lines = Files.lines(log)) { // lazily read; must be closed
long warnings = lines.filter(line -> line.startsWith("WARN")).count();
System.out.println("Warnings: " + warnings);
}
Files.delete(log);
}
}
Warnings: 2
How it works
- Lines are read lazily, so even a huge file uses little memory.
- The stream keeps the file open, so it is created in try-with-resources.
- Stream operations such as
filter()andcount()process the lines.
6. Using BufferedReader
BufferedReader is the classic, flexible way to read a file line by line.
import java.io.BufferedReader;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
public class ReadWithBufferedReader {
public static void main(String[] args) throws IOException {
Path scores = Files.createTempFile("scores", ".txt");
Files.writeString(scores, "72\n88\n95\n61\n");
int total = 0, count = 0;
try (BufferedReader in = Files.newBufferedReader(scores)) { // UTF-8
String line;
while ((line = in.readLine()) != null) { // one line at a time
total += Integer.parseInt(line);
count++;
}
}
System.out.println("Average score: " + (total / count));
Files.delete(scores);
}
}
Average score: 79
How it works
Files.newBufferedReader()opens the file with UTF-8 decoding.readLine()returnsnullat the end of the file, which ends the loop.- Only one line is held in memory at a time.
7. Using Scanner
Scanner splits a file into words and numbers and converts them to Java types for you.
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Scanner;
public class ReadWithScanner {
public static void main(String[] args) throws IOException {
Path prices = Files.createTempFile("prices", ".txt");
Files.writeString(prices, "pen 20\nnotebook 55\nbag 799\n");
try (Scanner in = new Scanner(prices, StandardCharsets.UTF_8)) { // Java 10
while (in.hasNext()) {
String item = in.next(); // reads a word
int price = in.nextInt(); // reads a number
System.out.println(item + " costs " + price);
}
}
Files.delete(prices);
}
}
pen costs 20 notebook costs 55 bag costs 799
How it works
new Scanner(path, StandardCharsets.UTF_8)(Java 10) opens the file.next()returns the next word andnextInt()parses the next number.Scanneris convenient but slower thanBufferedReaderfor large files.
8. Reading Binary Files
Images, PDFs and other binary files must be read as bytes, not text.
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
public class ReadBytes {
public static void main(String[] args) throws IOException {
Path icon = Files.createTempFile("icon", ".png");
Files.write(icon, new byte[] {(byte) 0x89, 'P', 'N', 'G', 13, 10, 26, 10});
byte[] all = Files.readAllBytes(icon); // the whole binary file
System.out.println("Bytes: " + all.length);
try (InputStream in = Files.newInputStream(icon)) { // or stream it
in.skipNBytes(1); // Java 12
System.out.println("Format: " + new String(in.readNBytes(3))); // "PNG"
}
Files.delete(icon);
}
}
Bytes: 8 Format: PNG
How it works
Files.readAllBytes()returns the whole file as abyte[].Files.newInputStream()reads it as a stream;skipNBytes()(Java 12) andreadNBytes()(Java 11) read exact amounts.- The bytes after the first one spell
PNG, the file type marker.
9. Common Mistakes and Best Practices
- Loading huge files with
readString()orreadAllLines(). UseFiles.lines()orBufferedReaderinstead. - Not closing streams and readers. Use try-with-resources, including for
Files.lines(). - Ignoring the charset. The
Filesmethods use UTF-8; pass a charset when a file uses another encoding. - Reading binary files as text. Decoding corrupts them; read bytes.
- Checking
Files.exists()first. HandleNoSuchFileExceptioninstead, because the file can change between the check and the read.
10. Summary
- Use
Files.readString()for small text files andFiles.readAllLines()when you need a list of lines. - Use
Files.lines()orBufferedReaderfor large files. - Use
Scannerto parse words and numbers. - Read binary files with
Files.readAllBytes()or anInputStream. - Close what you open, and specify the charset when it is not UTF-8.
Related Tutorials
- How to Write to a File in Java
- How to Read a CSV File in Java
- BufferedReader Class in Java
- Files Class in Java (NIO.2)