Java Files newInputStream() Method

Beginner
6 min read
Updated: Nov 2026
3 examples
Java 7+

Definition

In Java, Files.newInputStream(path) opens a file for reading and returns an InputStream. It is the NIO.2 replacement for new FileInputStream(file) and works with every API that accepts an InputStream.

The stream is not buffered: each small read() may go to the operating system. Read into a byte[], or wrap it in a BufferedInputStream or a Reader, for efficient code.

A static method of the final utility class java.nio.file.Files, available since Java 7. Call it on the class name, as in Files.newInputStream(...), after import java.nio.file.Files;. You never create a Files object.

Syntax

Open it in try-with-resources:

Java
try (InputStream in = Files.newInputStream(path)) {
    byte[] buf = new byte[8192];
    int n;
    while ((n = in.read(buf)) != -1) {
        // use buf[0..n)
    }
}
CallWhat it does
Files.newInputStream(p)Open for reading (option READ).
new BufferedInputStream(in)Add buffering for many small reads.
new InputStreamReader(in, cs)Turn bytes into characters.

Since Java 7. With no options it behaves as if StandardOpenOption.READ were given; options such as APPEND make no sense for reading.

Library declarations
Java
public static InputStream newInputStream(Path path, OpenOption... options) throws IOException

Parameters

ParameterDescription
pathThe file to open.
optionsOpen options; usually none.

Return Value

Return ValueDescription
InputStreamAn open stream positioned at the first byte.

Compare with Similar Methods

Byte-level reading:

MethodHow it differs
readAllBytes()Everything at once, no stream to manage.
newByteChannel()Seekable: jump to any position.
newOutputStream()The writing counterpart.

Java Examples

Example 1 — Count Bytes and Line Breaks

Read one byte at a time until read() returns -1.

Java
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;

public class NewInputStreamCount {
    public static void main(String[] args) throws IOException {
        Path dir = Files.createTempDirectory("demo");
        Path file = dir.resolve("abc.txt");
        Files.write(file, "a\nbb\nccc\n".getBytes(StandardCharsets.UTF_8));
        int bytes = 0;
        int newlines = 0;
        try (InputStream in = Files.newInputStream(file)) {
            int b;
            while ((b = in.read()) != -1) {
                bytes++;
                if (b == '\n') {
                    newlines++;
                }
            }
        }
        System.out.println("Bytes: " + bytes + ", line breaks: " + newlines);
        Files.delete(file);
        Files.delete(dir);
    }
}

How It Works

  1. An int, not a byte. read() returns 0 to 255 for data and -1 at the end, which is why the result is stored in an int.
  2. Nine bytes. a, bb, and ccc are six letters, plus three \n bytes.
  3. Fine for tiny files. One call per byte is slow on big files; the next example reads blocks.

Example 2 — Copy a File into Memory Block by Block

Read up to 4 bytes at a time into a buffer and collect them, the pattern used for files of any size.

Java
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;

public class NewInputStreamChunks {
    public static void main(String[] args) throws IOException {
        Path dir = Files.createTempDirectory("demo");
        Path file = dir.resolve("alphabet.txt");
        Files.write(file, "ABCDEFGHIJ".getBytes(StandardCharsets.UTF_8));
        ByteArrayOutputStream collected = new ByteArrayOutputStream();
        byte[] buf = new byte[4];
        try (InputStream in = Files.newInputStream(file)) {
            int n;
            while ((n = in.read(buf)) != -1) {
                collected.write(buf, 0, n);
            }
        }
        System.out.println("Total bytes: " + collected.size());
        System.out.println("Content: " + new String(collected.toByteArray(), StandardCharsets.UTF_8));
        Files.delete(file);
        Files.delete(dir);
    }
}

How It Works

  1. A tiny buffer on purpose. Real code uses 8192 bytes or more; 4 makes the loop run several times for 10 bytes.
  2. Use only n bytes. read(buf) returns how many bytes it filled, which can be less than the buffer size, so write(buf, 0, n) never copies stale data.
  3. -1 ends the loop. Once all 10 bytes are delivered, the next read returns -1 and the collected bytes form the original text.

Example 3 — Skip a Fixed Header and Read a Field

Jump over a known prefix with skip, then read the two bytes that follow it.

Java
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;

public class NewInputStreamSkip {
    public static void main(String[] args) throws IOException {
        Path dir = Files.createTempDirectory("demo");
        Path file = dir.resolve("record.dat");
        Files.write(file, "HEADER:v2;payload".getBytes(StandardCharsets.UTF_8));
        try (InputStream in = Files.newInputStream(file)) {
            long skipped = in.skip(7);
            char first = (char) in.read();
            char second = (char) in.read();
            System.out.println("Skipped " + skipped + " bytes");
            System.out.println("Version: " + first + second);
        }
        Files.delete(file);
        Files.delete(dir);
    }
}

How It Works

  1. Known layout. "HEADER:" is exactly seven bytes, so the version starts at byte 7.
  2. skip reports what it did. skip(7) returns the number of bytes actually skipped, 7 for this file.
  3. Two single reads. The next two calls return v and 2, cast to char because they are plain ASCII.

Frequently Asked Questions

No. Read into a byte array or wrap it in a BufferedInputStream when you make many small reads.
Wrap it: new BufferedReader(new InputStreamReader(Files.newInputStream(path), StandardCharsets.UTF_8)), or simply use Files.newBufferedReader.
Files.newInputStream works with Path, throws NoSuchFileException with a clear message, and supports other file systems such as ZIP file systems.
-1. Data bytes come back as values from 0 to 255.
Yes, otherwise the file stays open; on Windows that also blocks deleting it.

Next: Files.newOutputStream()

Open a file as an OutputStream for writing raw bytes.

newOutputStream() tutorial →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

12 people found this page helpful