00:00

How to Read a File in Java: 6 Ways with Examples

Last updated:

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

WayReturnsBest forSince
Files.readString()StringSmall text filesJava 11
Files.readAllLines()List<String>Small files, line by lineJava 7 (UTF-8 overload Java 8)
Files.lines()Stream<String>Large files with filteringJava 8
BufferedReaderOne line at a timeLarge files, full controlJava 1.1
ScannerWords and numbersParsing typed valuesJava 5
Files.readAllBytes() / InputStreambyte[]Binary filesJava 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.

ReadWithReadString.java
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);
    }
}
Output
Meeting moved to 3 PM.
Bring the sales report.
Characters: 47

How it works

  1. Files.readString() (Java 11) reads the file and decodes it as UTF-8.
  2. The returned text includes the line breaks, so it can be printed as it is.
  3. 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.

ReadWithReadAllLines.java
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);
    }
}
Output
Guests: 3
First: Anita, last: Chetan

How it works

  1. Files.readAllLines() returns a List<String>, one element per line, without line terminators.
  2. getFirst() and getLast() (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.

ReadWithLinesStream.java
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);
    }
}
Output
Warnings: 2

How it works

  1. Lines are read lazily, so even a huge file uses little memory.
  2. The stream keeps the file open, so it is created in try-with-resources.
  3. Stream operations such as filter() and count() process the lines.

6. Using BufferedReader

BufferedReader is the classic, flexible way to read a file line by line.

ReadWithBufferedReader.java
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);
    }
}
Output
Average score: 79

How it works

  1. Files.newBufferedReader() opens the file with UTF-8 decoding.
  2. readLine() returns null at the end of the file, which ends the loop.
  3. 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.

ReadWithScanner.java
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);
    }
}
Output
pen costs 20
notebook costs 55
bag costs 799

How it works

  1. new Scanner(path, StandardCharsets.UTF_8) (Java 10) opens the file.
  2. next() returns the next word and nextInt() parses the next number.
  3. Scanner is convenient but slower than BufferedReader for large files.

8. Reading Binary Files

Images, PDFs and other binary files must be read as bytes, not text.

ReadBytes.java
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);
    }
}
Output
Bytes: 8
Format: PNG

How it works

  1. Files.readAllBytes() returns the whole file as a byte[].
  2. Files.newInputStream() reads it as a stream; skipNBytes() (Java 12) and readNBytes() (Java 11) read exact amounts.
  3. The bytes after the first one spell PNG, the file type marker.

9. Common Mistakes and Best Practices

  • Loading huge files with readString() or readAllLines(). Use Files.lines() or BufferedReader instead.
  • Not closing streams and readers. Use try-with-resources, including for Files.lines().
  • Ignoring the charset. The Files methods 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. Handle NoSuchFileException instead, because the file can change between the check and the read.

10. Summary

  • Use Files.readString() for small text files and Files.readAllLines() when you need a list of lines.
  • Use Files.lines() or BufferedReader for large files.
  • Use Scanner to parse words and numbers.
  • Read binary files with Files.readAllBytes() or an InputStream.
  • Close what you open, and specify the charset when it is not UTF-8.

Related Tutorials

11. Official Java Documentation References