Course contentsShow
← Java
Lesson 2043 of 2,87041. NIO.2 and the Path APIFree lesson

Byte Streams: newInputStream and newOutputStream

Obtain InputStream and OutputStream from Path objects using Files for direct byte-level file access.

Byte Streams: newInputStream and newOutputStream

You'll learn how to obtain InputStream and OutputStream from Path objects for direct byte-level file access using NIO.2.

Why Use These Methods?

While Files.readAllBytes and Files.write are convenient for small files, sometimes you need fine-grained control over reading and writing bytes—perhaps to process a massive file incrementally, or to integrate with APIs that expect traditional byte streams. The Files class provides newInputStream() and newOutputStream() methods that bridge the modern Path API with classic stream-based I/O.

Core Concept

Think of these methods as "adapters" that let you use all the byte stream techniques you already know (buffering, wrapping with readers/writers, etc.) while working with the modern Path interface:

Path file = Paths.get("data.bin");

// Get an InputStream to read bytes
try (InputStream in = Files.newInputStream(file)) {
    int byteRead;
    while ((byteRead = in.read()) != -1) {
        // Process each byte
    }
}

// Get an OutputStream to write bytes
try (OutputStream out = Files.newOutputStream(file)) {
    byte[] data = {65, 66, 67}; // ABC
    out.write(data);
}

These methods return standard InputStream and OutputStream instances, so you can wrap them with BufferedInputStream, BufferedOutputStream, or bridge classes like InputStreamReader just as you've learned.

When to Use This Approach

Use newInputStream and newOutputStream when you need:

  • Byte-by-byte control without loading entire files into memory
  • Compatibility with existing code expecting stream objects
  • Integration with buffering or character encoding layers

Key Takeaway: Files.newInputStream() and Files.newOutputStream() provide Path-based access to traditional byte streams, combining NIO.2's modern path handling with classic I/O flexibility.