Home Java Files Methods newInputStream() 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:
try (InputStream in = Files.newInputStream(path)) {
byte[] buf = new byte[8192];
int n;
while ((n = in.read(buf)) != -1) {
// use buf[0..n)
}
} Call What 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 public static InputStream newInputStream(Path path, OpenOption... options) throws IOException Parameters Parameter Description pathThe file to open. optionsOpen options; usually none.
Return Value Return Value Description InputStreamAn open stream positioned at the first byte.
Important
Throws NoSuchFileException if the file is missing, IllegalArgumentException or UnsupportedOperationException for invalid options (such as WRITE or APPEND). On Windows an open stream blocks deleting the file, so close it first.
Compare with Similar Methods Byte-level reading:
Java Examples 1. Byte by byte 2. Read in blocks 3. Skip a header Example 1 — Count Bytes and Line Breaks Read one byte at a time until read() returns -1.
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);
}
} Run with java NewInputStreamCount. The output is the same on Windows, macOS, and Linux.
Bytes: 9, line breaks: 3 How It Works 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.Nine bytes. a, bb, and ccc are six letters, plus three \n bytes.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.
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);
}
} Run with java NewInputStreamChunks. The output is the same on Windows, macOS, and Linux.
Total bytes: 10
Content: ABCDEFGHIJ How It Works A tiny buffer on purpose. Real code uses 8192 bytes or more; 4 makes the loop run several times for 10 bytes.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.-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.
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);
}
} Run with java NewInputStreamSkip. The output is the same on Windows, macOS, and Linux.
Skipped 7 bytes
Version: v2 How It Works Known layout. "HEADER:" is exactly seven bytes, so the version starts at byte 7.skip reports what it did. skip(7) returns the number of bytes actually skipped, 7 for this file.Two single reads. The next two calls return v and 2, cast to char because they are plain ASCII.Frequently Asked Questions Is the stream from Files.newInputStream buffered? No. Read into a byte array or wrap it in a BufferedInputStream when you make many small reads.
How do I read text with Files.newInputStream? Wrap it: new BufferedReader(new InputStreamReader(Files.newInputStream(path), StandardCharsets.UTF_8)), or simply use Files.newBufferedReader.
Files.newInputStream or FileInputStream? Files.newInputStream works with Path, throws NoSuchFileException with a clear message, and supports other file systems such as ZIP file systems.
What does read() return at the end of the file? -1. Data bytes come back as values from 0 to 255.
Do I need to close the InputStream? Yes, otherwise the file stays open; on Windows that also blocks deleting it.
About the author Developer, cloud engineer, and technical writer
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
Helpful Share Copy link Suggestion