Java InputStream

Su Suriya Ravichandran Updated 18 Nov 2026
10 min read ·Lesson 153 of 306

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

ClassReads bytes from
FileInputStream, Files.newInputStream(path)A file
ByteArrayInputStreamA byte[] in memory — useful in tests and for data already loaded
socket.getInputStream()A TCP connection
HttpResponse<InputStream> bodyAn HTTP response (Java 11 HTTP client)
Class.getResourceAsStream(name)A resource on the classpath (inside the JAR or resources folder)
System.inStandard input
InputStream.nullInputStream() (Java 11+)Nothing — always at end of stream

And the decorators, which wrap another InputStream to add behaviour:

DecoratorAdds
BufferedInputStreamAn in-memory buffer for efficient small reads, plus mark/reset
DataInputStreamReading Java primitive types (Data Streams lesson)
ObjectInputStreamDeserializing objects (Object Streams lesson)
GZIPInputStream, ZipInputStream, InflaterInputStreamDecompression
CipherInputStreamDecryption
DigestInputStreamComputing a hash while reading
SequenceInputStreamReading several streams one after another
PushbackInputStream"Un-reading" bytes for parsers

The Methods

MethodBehaviour
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 header HEADER:.
  • mark(100) remembers the current position (valid as long as no more than 100 bytes are read before reset), and reset() returns to it, so ABC is read twice. ByteArrayInputStream and BufferedInputStream support marking; FileInputStream and socket streams don't — check markSupported() or wrap the stream in a BufferedInputStream.
  • skipNBytes(2) skips DE, leaving 5 bytes, which available() 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]
  1. TrickleInputStream is also an example of writing your own InputStream: implement read(), and override read(byte[], int, int) for efficiency. Note data[pos++] & 0xFF — the byte is converted to the range 0–255 so that a byte value of -1 isn't confused with end of stream.
  2. 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.
  3. readNBytes(8) keeps calling read until it has 8 bytes or the stream ends.
  4. The manual loop does the same explicitly, using the off and len parameters to fill the rest of the array, and throws EOFException if 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:

  1. Files.newInputStream reads the compressed bytes from the file.
  2. BufferedInputStream reads them in large blocks.
  3. GZIPInputStream decompresses them back into the original bytes.
  4. InputStreamReader decodes those bytes into characters as UTF-8, and BufferedReader splits 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, or props.load(null) would throw a confusing NullPointerException.
  • 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:

  1. FilterInputStream is the base class for decorators: it stores the wrapped stream in the field in and forwards every method to it. You override only the methods whose behaviour changes.
  2. Every read path is counted — read(), read(byte[], int, int) and skip — 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.)
  3. The exception is an IOException subclass. Code such as Files.copy already propagates IOException, so the limit failure travels up naturally, and callers can catch the specific type to return a "413 Payload Too Large" response.
  4. markSupported() returns false: a reset() would re-read bytes that were already counted, which would make the count wrong.
  5. The upload is written to a temporary .part file and moved into place only after it's complete and within the limit. When the limit is exceeded, Files.copy stops with the exception, the move never happens, and finally deletes the partial file. No oversized or half-written file is left behind.
  6. 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).

0 Comments

Reviewed before they appear

No comments yet.

Java
Java Introduction Java Features Java Syntax Java Comments Java Statements Java Output Java Variables Java Data Types Java Type Casting Java Operators Java Strings Java Numbers Java Math Java Booleans Java User Input Java Conditions Java If Else Java Switch Java While Loop Java For Loop Java Break Java Continue Java Arrays Java Methods Java Parameters Java Return Values Java Scope Java Recursion Install Java Install JDK Java IDEs Java JDK Java JRE Java JVM Java Compiler Java File Compile Java Run Java JShell Basics Java Packages Java OOP Java Classes Java Objects Class Methods Constructors Constructor Overload this Keyword static Keyword final Keyword Encapsulation Inheritance Polymorphism Abstraction Access Modifiers super Keyword Method Overload Method Override Instanceof Operator Nested Classes Inner Classes Anonymous Classes Enums Records Array Basics Array Length Loop Arrays Multidimensional Arrays Array Copy Array Sorting Array Search ArrayList LinkedList HashSet TreeSet HashMap TreeMap Queue Interface Deque Interface Stack Class Iterator List Interface Set Interface Map Interface Collections Class Comparable Comparator Generics Basics Generic Classes Generic Methods Wildcards String Basics String Length String Methods String Concatenation String Compare String Search String Replace String Split String Format StringBuilder StringBuffer Text Blocks Regular Expressions Number Types Integer Class Float Class Double Class BigInteger BigDecimal Math Class Random Numbers Number Format Date Basics LocalDate LocalTime LocalDateTime ZonedDateTime Date Formatting Date Parsing Period Class Duration Class Java Instant Class Java Exception Basics Java try...catch Java Multiple Catch Blocks Java finally Block Java throw Keyword Java throws Keyword Java Checked Exceptions Java Unchecked Exceptions Java Custom Exceptions Java try-with-resources Java Exception Chaining Java File Basics Java Create Files Java Read Files Java Write Files Java Delete Files Java File Paths Java File Class Java BufferedReader Java BufferedWriter Java FileInputStream Java FileOutputStream Java Object Streams Java Directory Handling Java NIO Basics Java Files API Java Input Java Scanner Class Java Console Input Java PrintStream Java InputStream Java OutputStream Java Reader Class Java Writer Class Java Buffered Streams Java Data Streams Java Generics Introduction Java Generic Types Java Generic Methods Java Bounded Types Java Wildcards Java Type Erasure Java Generic Interfaces Java Generic Collections Java Lambda Basics Java Lambda Syntax Java Functional Interfaces Java Method References Java Stream API Java Stream Creation Java Stream Filter Java Stream Map Java Stream Reduce Java Stream Sort Java Stream Collect Java Collectors Class Java Optional Class Java Parallel Streams Java Threads: Thread Basics Create a Thread in Java Java Thread Class Java Runnable Interface Java Thread States Java Thread Sleep Java Thread Join Java Thread Priority Java Synchronization Java Thread Safety Java Race Conditions Java Deadlocks Java Executor Service Java Thread Pools Java Callable Interface Java Future Interface Java CompletableFuture Java Concurrent Collections Java Atomic Classes Java Virtual Threads Java Networking Basics Java URL Class Java URI Class Java HttpClient Java HTTP Requests Java HTTP Responses Java Socket Basics Java ServerSocket Java DatagramSocket Java WebSocket Basics Java JDBC Basics Java JDBC Setup Java Database Connection Java JDBC Connection Interface Java JDBC Statement Java PreparedStatement Java ResultSet Java JDBC CRUD Operations Java JDBC Transactions Java JDBC Batch Update Java Connection Pooling with HikariCP Java JPA Basics: Entities, EntityManager and JPQL Java Hibernate Basics: SessionFactory, Session and HQL Package in Java: Basics Explained with Examples Create Package in Java: Step-by-Step Guide with Examples Import Package in Java: The import Statement Explained Access Control in Java: Packages, Classes and Members JAR File in Java: Create, Run and Inspect JAR Files Java Modules: Introduction to the Java Module System module-info in Java: Every Module Directive Explained Java Module Path: How --module-path Finds Your Modules Java Classpath: How -cp and CLASSPATH Find Your Classes Java Annotations: Basics of @ Metadata in Java Java Built-in Annotations: @Override, @Deprecated and More Java Custom Annotations: Create Your Own @interface Java Annotation Targets: @Target and ElementType Explained Java Reflection API: Inspect and Use Classes at Runtime Java Class Metadata: Names, Modifiers, Hierarchy and Generic Java Dynamic Objects: Create Objects Dynamically With Reflec Java Dynamic Proxy: Intercept Method Calls With Proxy and In Java Security Java Secure Coding Java Password Hashing Java Input Validation Java Cryptography Basics Java KeyStore Basics Java TLS Basics Java SecureRandom Java JUnit Basics Java JUnit Test Methods JUnit Assertions JUnit Test Fixtures JUnit Parameterized Tests Mockito in Java Java Mock Objects Java Integration Testing Java Code Coverage Maven in Java Create a Maven Project in Java Maven Dependencies Maven Plugins Gradle in Java Gradle Build Gradle Dependencies Build Executable JAR in Java Build WAR File in Java HTTP Basics in Java Java Servlet Basics Servlet Lifecycle in Java HttpServletRequest in Java HttpServletResponse in Java JSP in Java JSTL in JSP REST API in Java JSON in Java Java Web Application Spring Framework Basics Spring Boot Tutorial Spring MVC Spring Data JPA Spring Security Spring Boot REST API Jakarta EE Basics Java Deployment JAR Deployment Java WAR Deployment Run Java as a Service Docker Java: Dockerize a Java Application Java Environment Variables and Configuration Java Logging Basics Java Production Setup Java JVM Options Java JVM Monitoring Java Hello World App Java Calculator App Java Number Guess Game Java Student Manager Java Library System Java Bank App Java Todo App Java File Manager Java Quiz App Java REST API Project Java Chat Server Java Employee Manager Java E-commerce API
Ask about this post
AI Ask about this post

Ask questions about Java InputStream and get answers drawn from it.

Signed-in readers only.