00:00

Java NIO vs IO: Differences and When to Use Each

Last updated:

Java has two families of file and I/O APIs: the original java.io package and the newer NIO APIs. Both are fully supported in Java 25, and real projects use both. Knowing their differences helps you choose the right tool and read older code with confidence.

1. What Are Java IO and Java NIO?

  • java.io (Java 1.0) offers File and the byte and character streams. It is simple and stream-oriented: you read or write data in order, and each call blocks until it completes.
  • NIO (Java 1.4, package java.nio) added buffers, channels and selectors, which allow non-blocking I/O for servers that handle many connections.
  • NIO.2 (Java 7, package java.nio.file) added Path and Files, a modern replacement for File with clearer errors and many one-line helpers.

For everyday file work, "NIO" usually means NIO.2.

2. IO and NIO at a Glance

Java IO compared with NIO and NIO.2Two columns. java.io, available since Java 1.0, represents a file with File, reads and writes with streams, uses a blocking one-way model, often reports errors as true, false or null, has limited symbolic link support and requires you to write folder walking yourself. NIO (Java 1.4) and NIO.2 (Java 7) represent a file with Path, reads and writes with Files and channels, supports blocking or non-blocking I/O, throws descriptive exceptions, fully supports symbolic links and walks folder trees with Files.walk.java.ioJava 1.0+Represents a fileFileReads and writesstreamsModelblocking, one wayErrorsoften true/false or nullSymbolic linkslimited supportWalk a folder treewrite it yourselfNIO / NIO.2Java 1.4+ / Java 7+Represents a filePathReads and writesFiles, channelsModelblocking or non-blockingErrorsdescriptive exceptionsSymbolic linksfull supportWalk a folder treeFiles.walk()

Swipe sideways to see the whole diagram.

3. Java IO vs NIO: Detailed Comparison

Aspectjava.iojava.nio / java.nio.file
File representationFilePath (immutable, thread-safe)
Data processingStream-oriented, one directionBuffer- and channel-oriented; streams also available
BlockingAlways blockingChannels can be non-blocking with selectors
Error reportingMany methods return false or nullSpecific exceptions such as NoSuchFileException
Common tasksSeveral classes and loopsOne-line helpers: readString, copy, walk
Metadata and linksBasicAttributes, permissions and symbolic links

4. Example: The Same Task Both Ways

A billing tool counts the orders in a text file, once with classic java.io and once with NIO.2.

LineCountTwoWays.java
import java.io.BufferedReader;
import java.io.File;
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 LineCountTwoWays {
    public static void main(String[] args) throws IOException {
        Path data = Files.createTempFile("orders", ".txt");
        Files.writeString(data, "order-1\norder-2\norder-3\norder-4\n");

        // Classic java.io: File + FileReader + BufferedReader + loop
        int ioCount = 0;
        File file = data.toFile();
        try (BufferedReader in = new BufferedReader(new FileReader(file, StandardCharsets.UTF_8))) {
            while (in.readLine() != null) {
                ioCount++;
            }
        }

        // NIO.2: Path + Files.lines()
        long nioCount;
        try (Stream<String> lines = Files.lines(data)) {
            nioCount = lines.count();
        }

        System.out.println("java.io count:  " + ioCount);
        System.out.println("NIO.2 count:    " + nioCount);
        Files.delete(data);
    }
}
Output
java.io count:  4
NIO.2 count:    4

How the code works

  1. The java.io version combines File, FileReader and BufferedReader with a counting loop.
  2. The NIO.2 version uses Files.lines(), which returns a stream of lines that is closed by try-with-resources.
  3. Both give the same answer; the NIO.2 code is shorter.

5. Example: How Errors Are Reported

A clean-up job tries to delete a report that does not exist. The two APIs report the problem very differently.

ErrorMessages.java
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;

public class ErrorMessages {
    public static void main(String[] args) throws IOException {
        Path folder = Files.createTempDirectory("reports");
        Path missing = folder.resolve("q3-summary.pdf");

        // java.io: failure is only a boolean
        boolean deleted = new File(missing.toString()).delete();
        System.out.println("File.delete() returned: " + deleted);

        // NIO.2: failure is an exception that explains why
        try {
            Files.delete(missing);
        } catch (IOException e) {
            System.out.println("Files.delete() threw:   " + e.getClass().getSimpleName());
        }
        Files.delete(folder);
    }
}
Output
File.delete() returned: false
Files.delete() threw:   NoSuchFileException

How the code works

  1. File.delete() only returns false; the reason is lost.
  2. Files.delete() throws NoSuchFileException, which states exactly what went wrong.

6. Which One Should You Use?

  • For new file and folder code, use NIO.2: Path and Files.
  • For processing data step by step, the java.io streams remain the standard; Files creates them for you.
  • For servers handling thousands of connections, consider NIO channels, or virtual threads (Java 21) with simple blocking code.
  • Convert between the APIs with file.toPath() and path.toFile().

7. Java Version Improvements and Java 25 Updates

Java versionChange
Java 1.0java.io: File and streams.
Java 1.4NIO: buffers, channels and selectors.
Java 7NIO.2: Path, Files and file attributes.
Java 8 to 12Files.lines(), walk(), readString(), writeString(), Path.of() and mismatch().
Java 21Virtual threads make simple blocking I/O scale to many tasks.
Java 25Both APIs remain fully supported; Path.resolve(first, more...) arrived in Java 22.

8. Summary

  • java.io is the original, stream-based API built around File.
  • NIO added channels and buffers; NIO.2 added Path and Files.
  • NIO.2 gives clearer errors and shorter code for most file tasks.
  • Both are current in Java 25 and work together.

Related Tutorials

9. Official Java Documentation References