Java InputStream
The InputStream Abstraction
java.io.InputStream is the abstract base class for every source of bytes in Java. Files, network connections, HTTP responses, compressed archives, arrays in memory and resources inside a JAR all deliver their data as an InputStream.
The value of this abstraction is that code written against InputStream works with any source. A method that computes a checksum, parses an image header or copies data doesn't need to know whether the bytes come from a disk, a socket or a test array:
static long countBytes(InputStream in) throws IOException {
long n = 0;
while (in.read() != -1) n++;
return n;
}
// works with new FileInputStream(...), socket.getInputStream(), new ByteArrayInputStream(...), ...
InputStream is abstract: subclasses must implement only one method, int read(), and inherit working versions of everything else.
Common InputStream Classes
| Class | Reads bytes from |
|---|---|
FileInputStream, Files.newInputStream(path) | A file |
ByteArrayInputStream | A byte[] in memory — useful in tests and for data already loaded |
socket.getInputStream() | A TCP connection |
HttpResponse<InputStream> body | An HTTP response (Java 11 HTTP client) |
Class.getResourceAsStream(name) | A resource on the classpath (inside the JAR or resources folder) |
System.in | Standard input |
InputStream.nullInputStream() (Java 11+) | Nothing — always at end of stream |
And the decorators, which wrap another InputStream to add behaviour:
| Decorator | Adds |
|---|---|
BufferedInputStream | An in-memory buffer for efficient small reads, plus mark/reset |
DataInputStream | Reading Java primitive types (Data Streams lesson) |
ObjectInputStream | Deserializing objects (Object Streams lesson) |
GZIPInputStream, ZipInputStream, InflaterInputStream | Decompression |
CipherInputStream | Decryption |
DigestInputStream | Computing a hash while reading |
SequenceInputStream | Reading several streams one after another |
PushbackInputStream | "Un-reading" bytes for parsers |
The Methods
| Method | Behaviour |
|---|---|
int read() | Next byte as 0–255, or -1 at the end. Blocks until data is available |
int read(byte[] b) / int read(byte[] b, int off, int len) | Reads up to len bytes; returns the number read, or -1 at the end |
byte[] readAllBytes() (Java 9+) | Everything until the end |
byte[] readNBytes(int n) (Java 11+) / int readNBytes(byte[], off, len) (Java 9+) | Up to n bytes, looping internally; fewer only at the end of the stream |
long skip(long n) / void skipNBytes(long n) (Java 12+) | Skip bytes. skip may skip fewer; skipNBytes skips exactly n or throws EOFException |
int available() | An estimate of bytes readable without blocking — not the total size |
long transferTo(OutputStream out) (Java 9+) | Copies everything remaining to out |
void mark(int readLimit) / void reset() / boolean markSupported() | Remember a position and return to it, if the stream supports it |
void close() | Releases the underlying resource |
import java.io.*;
import java.nio.charset.StandardCharsets;
public class I1 {
public static void main(String[] args) throws IOException {
byte[] data = "HEADER:ABCDEFGHIJ".getBytes(StandardCharsets.US_ASCII);
try (InputStream in = new ByteArrayInputStream(data)) {
System.out.println("markSupported: " + in.markSupported());
byte[] header = in.readNBytes(7);
System.out.println("header: " + new String(header, StandardCharsets.US_ASCII));
in.mark(100);
System.out.println("next 3: " + new String(in.readNBytes(3), StandardCharsets.US_ASCII));
in.reset();
System.out.println("after reset, next 3 again: " + new String(in.readNBytes(3), StandardCharsets.US_ASCII));
in.skipNBytes(2);
System.out.println("available: " + in.available());
System.out.println("rest: " + new String(in.readAllBytes(), StandardCharsets.US_ASCII));
}
System.out.println("empty stream read: " + InputStream.nullInputStream().read());
}
}
Output:
markSupported: true
header: HEADER:
next 3: ABC
after reset, next 3 again: ABC
available: 5
rest: FGHIJ
empty stream read: -1
readNBytes(7)reads the 7-byte headerHEADER:.mark(100)remembers the current position (valid as long as no more than 100 bytes are read beforereset), andreset()returns to it, soABCis read twice.ByteArrayInputStreamandBufferedInputStreamsupport marking;FileInputStreamand socket streams don't — checkmarkSupported()or wrap the stream in aBufferedInputStream.skipNBytes(2)skipsDE, leaving 5 bytes, whichavailable()reports correctly for an in-memory stream.readAllBytes()returns the remainder,FGHIJ.nullInputStream()is an empty stream, handy as a default value or in tests.
Partial Reads
The most important rule of InputStream: read(byte[]) may return fewer bytes than you asked for, even when more data is coming. Files usually fill the buffer, but network streams return whatever has arrived so far. Code that assumes the buffer is full works in tests with files and then fails in production with sockets.
This example simulates a network connection that delivers at most 3 bytes per call:
import java.io.*;
import java.util.Arrays;
public class Slow {
// Simulates a network stream that delivers at most 3 bytes per read call
static class TrickleInputStream extends InputStream {
private final byte[] data;
private int pos = 0;
TrickleInputStream(byte[] data) { this.data = data; }
@Override public int read() {
return pos < data.length ? data[pos++] & 0xFF : -1;
}
@Override public int read(byte[] b, int off, int len) {
if (len == 0) return 0;
if (pos >= data.length) return -1;
int n = Math.min(Math.min(len, 3), data.length - pos);
System.arraycopy(data, pos, b, off, n);
pos += n;
return n;
}
}
public static void main(String[] args) throws IOException {
byte[] message = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
InputStream in1 = new TrickleInputStream(message);
byte[] buf = new byte[8];
int n = in1.read(buf);
System.out.println("read(buf of 8) returned " + n + ": " + Arrays.toString(buf));
InputStream in2 = new TrickleInputStream(message);
byte[] all = in2.readNBytes(8);
System.out.println("readNBytes(8) returned " + all.length + ": " + Arrays.toString(all));
InputStream in3 = new TrickleInputStream(message);
byte[] exact = new byte[8];
int filled = 0;
while (filled < exact.length) {
int r = in3.read(exact, filled, exact.length - filled);
if (r == -1) throw new EOFException("stream ended after " + filled + " bytes");
filled += r;
}
System.out.println("manual loop filled " + filled + ": " + Arrays.toString(exact));
}
}
Output:
read(buf of 8) returned 3: [1, 2, 3, 0, 0, 0, 0, 0]
readNBytes(8) returned 8: [1, 2, 3, 4, 5, 6, 7, 8]
manual loop filled 8: [1, 2, 3, 4, 5, 6, 7, 8]
TrickleInputStreamis also an example of writing your ownInputStream: implementread(), and overrideread(byte[], int, int)for efficiency. Notedata[pos++] & 0xFF— the byte is converted to the range 0–255 so that a byte value of-1isn't confused with end of stream.- A single
read(buf)returns only 3 bytes. The rest of the array is untouched (zeros). Code that processed all 8 positions would use garbage data. readNBytes(8)keeps callingreaduntil it has 8 bytes or the stream ends.- The manual loop does the same explicitly, using the
offandlenparameters to fill the rest of the array, and throwsEOFExceptionif the stream ends early — essential when reading fixed-size structures such as message headers.
Layering Decorators
Because decorators take an InputStream and are themselves InputStreams, they can be stacked, each adding one capability:
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.*;
import java.util.zip.*;
public class Gz {
public static void main(String[] args) throws IOException {
String log = "GET /java/lesson-153 200\n".repeat(2_000);
try (OutputStream out = new GZIPOutputStream(Files.newOutputStream(Path.of("access.log.gz")))) {
out.write(log.getBytes(StandardCharsets.UTF_8));
}
System.out.println("original " + log.length() + " bytes, compressed " + Files.size(Path.of("access.log.gz")) + " bytes");
try (BufferedReader reader = new BufferedReader(new InputStreamReader(
new GZIPInputStream(new BufferedInputStream(Files.newInputStream(Path.of("access.log.gz")))),
StandardCharsets.UTF_8))) {
long lines = reader.lines().count();
System.out.println("read back " + lines + " lines through 4 layered streams");
}
}
}
Output:
original 50000 bytes, compressed 190 bytes
read back 2000 lines through 4 layered streams
Reading from the inside out:
Files.newInputStreamreads the compressed bytes from the file.BufferedInputStreamreads them in large blocks.GZIPInputStreamdecompresses them back into the original bytes.InputStreamReaderdecodes those bytes into characters as UTF-8, andBufferedReadersplits them into lines.
The repetitive log compresses from 50,000 bytes to 190. Compressed logs (.gz) are standard in log rotation, and this chain reads them without extracting them to disk first. Closing the outermost object closes the whole chain, so only it needs to be in try-with-resources.
Reading Classpath Resources
Files packaged with an application — default configuration, templates, SQL scripts, test data — are read as resources from the classpath, not as files, because inside a JAR they aren't separate files on disk.
import java.io.*;
import java.util.Properties;
public class Res {
public static void main(String[] args) throws IOException {
Properties props = new Properties();
try (InputStream in = Res.class.getResourceAsStream("/app.properties")) {
if (in == null) throw new FileNotFoundException("app.properties not found on the classpath");
props.load(in);
}
System.out.println("app.name = " + props.getProperty("app.name"));
System.out.println("missing resource: " + Res.class.getResourceAsStream("/nope.properties"));
}
}
With app.properties (containing app.name=GOCOURSE Shop) in a folder on the classpath — in Maven and Gradle projects, src/main/resources — the output is:
app.name = GOCOURSE Shop
missing resource: null
- A leading
/means "from the root of the classpath"; without it, the name is relative to the class's package. - A missing resource returns
null, not an exception. Check it, as the example does, orprops.load(null)would throw a confusingNullPointerException. - This works the same whether the application runs from a folder in an IDE or from a packaged JAR, which
new FileInputStream("src/main/resources/app.properties")doesn't.
Practical Example: Enforcing an Upload Size Limit
A web application that accepts uploads must not trust the size the client claims. A malicious or buggy client can send an endless stream and fill the server's disk. A decorator that counts bytes as they pass through and fails once a limit is exceeded protects any code that reads the stream, without that code having to change.
import java.io.*;
import java.nio.file.*;
public class Limit {
static class SizeLimitExceededException extends IOException {
SizeLimitExceededException(long limit) { super("upload exceeds the limit of " + limit + " bytes"); }
}
static class LimitedInputStream extends FilterInputStream {
private final long limit;
private long count = 0;
LimitedInputStream(InputStream in, long limit) {
super(in);
this.limit = limit;
}
private void track(long n) throws SizeLimitExceededException {
if (n > 0) {
count += n;
if (count > limit) throw new SizeLimitExceededException(limit);
}
}
@Override public int read() throws IOException {
int b = super.read();
if (b != -1) track(1);
return b;
}
@Override public int read(byte[] b, int off, int len) throws IOException {
int n = super.read(b, off, len);
track(n);
return n;
}
@Override public long skip(long n) throws IOException {
long skipped = super.skip(n);
track(skipped);
return skipped;
}
@Override public boolean markSupported() { return false; }
}
static long saveUpload(InputStream body, Path target, long maxBytes) throws IOException {
Path tmp = Files.createTempFile(target.toAbsolutePath().getParent(), "upload-", ".part");
try (InputStream in = new LimitedInputStream(body, maxBytes)) {
long n = Files.copy(in, tmp, StandardCopyOption.REPLACE_EXISTING);
Files.move(tmp, target, StandardCopyOption.REPLACE_EXISTING);
return n;
} finally {
Files.deleteIfExists(tmp);
}
}
public static void main(String[] args) throws IOException {
long max = 1_000_000;
System.out.println("saved " + saveUpload(new ByteArrayInputStream(new byte[250_000]), Path.of("avatar.png"), max) + " bytes");
try {
saveUpload(new ByteArrayInputStream(new byte[5_000_000]), Path.of("video.mp4"), max);
} catch (SizeLimitExceededException e) {
System.out.println("rejected: " + e.getMessage());
}
System.out.println("video.mp4 exists: " + Files.exists(Path.of("video.mp4")));
try (var s = Files.list(Path.of("."))) {
System.out.println("leftover .part files: " + s.filter(p -> p.toString().endsWith(".part")).count());
}
}
}
Output:
saved 250000 bytes
rejected: upload exceeds the limit of 1000000 bytes
video.mp4 exists: false
leftover .part files: 0
How it works:
FilterInputStreamis the base class for decorators: it stores the wrapped stream in the fieldinand forwards every method to it. You override only the methods whose behaviour changes.- Every read path is counted —
read(),read(byte[], int, int)andskip— so the limit can't be bypassed by any of them. (FilterInputStream.read(byte[])delegates to the three-argument version, so it's covered too.) - The exception is an
IOExceptionsubclass. Code such asFiles.copyalready propagatesIOException, so the limit failure travels up naturally, and callers can catch the specific type to return a "413 Payload Too Large" response. markSupported()returnsfalse: areset()would re-read bytes that were already counted, which would make the count wrong.- The upload is written to a temporary
.partfile and moved into place only after it's complete and within the limit. When the limit is exceeded,Files.copystops with the exception, the move never happens, andfinallydeletes the partial file. No oversized or half-written file is left behind. - The 5 MB upload is rejected after just over 1 MB has been read — the server never reads or stores the rest.
Web frameworks offer configuration for this (for example, Spring Boot's spring.servlet.multipart.max-file-size), and they implement it with exactly this kind of counting stream. Writing your own is useful when you process streams outside a framework — files downloaded from other services, message payloads, archive entries (where it also protects against "zip bombs" that expand enormously when decompressed).