00:00

InputStream Class in Java: Methods and Examples

Last updated:

Whether bytes come from a file, a network socket, a ZIP entry or an array in memory, Java reads them through one abstract class: java.io.InputStream. Code written against InputStream works with all of these sources without changes.

This tutorial covers what InputStream is, its subclasses, every important method and two practical examples.

1. What Is InputStream in Java?

InputStream is the abstract superclass of all classes that read bytes. It has been part of Java since version 1.0 and implements Closeable (and therefore AutoCloseable), so it works with try-with-resources.

It declares one abstract method, read(), which returns the next byte as an int from 0 to 255, or -1 at the end of the stream. Every other method is built on top of it, and subclasses usually override the array versions for speed.

Declaration
public abstract class InputStream implements Closeable

2. InputStream Class Hierarchy

InputStream hierarchy and methodsLeft: InputStream, an abstract class that implements Closeable, with subclasses FileInputStream, ByteArrayInputStream, FilterInputStream (extended by BufferedInputStream and DataInputStream), ObjectInputStream, PipedInputStream and SequenceInputStream. Right: its methods grouped as read (read, readNBytes, readAllBytes), move (skip, skipNBytes, mark, reset, markSupported) and copy and finish (transferTo, available, close, nullInputStream).InputStreamabstract class, implements CloseableFileInputStreama fileByteArrayInputStreama byte[]FilterInputStreamwrappersBufferedInputStreambufferingDataInputStreamprimitivesObjectInputStreamobjectsPipedInputStreamthreadsSequenceInputStreamjoins streamsReadread(), read(byte[])read(byte[], off, len)readNBytes(), readAllBytes() Java 9+Moveskip(), skipNBytes() Java 12mark(), reset(), markSupported()Copy and finishtransferTo() Java 9available(), close()nullInputStream() Java 11

Swipe sideways to see the whole diagram.

3. Methods of the InputStream Class

MethodReturnsDescription
read()intNext byte (0–255), or -1 at the end.
read(byte[] b, int off, int len)intReads up to len bytes; returns how many, or -1.
readNBytes(int len)byte[]Reads up to len bytes, blocking until they arrive or the stream ends (Java 11).
readAllBytes()byte[]Reads everything that is left (Java 9).
skip(long n) / skipNBytes(long n)long / voidSkips bytes; skipNBytes (Java 12) skips exactly n or throws EOFException.
available()intAn estimate of bytes readable without blocking; not the total size.
mark(int) / reset()voidRemember a position and return to it, if markSupported() is true.
transferTo(OutputStream out)longCopies all remaining bytes and returns the count (Java 9).
nullInputStream()InputStreamA static factory for an empty stream (Java 11).
close()voidReleases the underlying resource.

4. Example: One Method for Every Source

A payment system verifies invoices with a CRC32 checksum. Because the crc32() method accepts any InputStream, the same code checks data held in memory and data saved to a file.

ChecksumAnySource.java
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.zip.CRC32;

public class ChecksumAnySource {

    // Works with ANY InputStream: memory, file, network ...
    static long crc32(InputStream in) throws IOException {
        CRC32 crc = new CRC32();
        byte[] buffer = new byte[1024];
        int count;
        while ((count = in.read(buffer)) != -1) {
            crc.update(buffer, 0, count);
        }
        return crc.getValue();
    }

    public static void main(String[] args) throws IOException {
        byte[] invoice = "INV-2026-0042;amount=1499.00;currency=INR".getBytes(StandardCharsets.UTF_8);
        Path saved = Files.createTempFile("invoice", ".txt");
        Files.write(saved, invoice);

        try (InputStream fromMemory = new ByteArrayInputStream(invoice);
             InputStream fromFile = Files.newInputStream(saved)) {
            long a = crc32(fromMemory);
            long b = crc32(fromFile);
            System.out.printf("Memory checksum: %08x%n", a);
            System.out.printf("File checksum:   %08x%n", b);
            System.out.println("Same content:    " + (a == b));
        }
        Files.delete(saved);
    }
}
Output
Memory checksum: 08092a81
File checksum:   08092a81
Same content:    true

How the code works

  1. crc32() depends only on the abstract InputStream type, so it never needs to know where the bytes come from.
  2. read(buffer) returns how many bytes were actually read, and only those bytes are passed to CRC32.update().
  3. ByteArrayInputStream and Files.newInputStream() supply the same bytes, so the checksums match.

5. Example: Parsing a Message with Java 9+ Methods

A monitoring tool receives small binary messages: a 4-byte type, 2 reserved bytes and a text body. Java 9–12 methods make parsing short and safe.

MessageParser.java
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;

public class MessageParser {
    public static void main(String[] args) throws IOException {
        // A tiny protocol: 4-byte type, 2 reserved bytes, then the body
        byte[] packet = "PING\0\0server-07 is alive".getBytes(StandardCharsets.US_ASCII);

        try (InputStream in = new ByteArrayInputStream(packet)) {
            String type = new String(in.readNBytes(4), StandardCharsets.US_ASCII);   // Java 11
            in.skipNBytes(2);                                                         // Java 12
            String body = new String(in.readAllBytes(), StandardCharsets.US_ASCII);  // Java 9
            System.out.println("Type: " + type);
            System.out.println("Body: " + body);
            System.out.println("End of stream: " + (in.read() == -1));
        }
    }
}
Output
Type: PING
Body: server-07 is alive
End of stream: true

How the code works

  1. readNBytes(4) reads exactly the type field, without a manual loop.
  2. skipNBytes(2) discards the reserved bytes and would throw EOFException if the message were too short.
  3. readAllBytes() returns the rest of the message, after which read() returns -1.

6. Important Points

  • read(byte[]) may return fewer bytes than requested, even before the end of the stream. Always use its return value.
  • Reading methods block until data is available, the stream ends or an error occurs.
  • available() is an estimate and must not be used as the size of a file or message.
  • mark() and reset() work only when markSupported() returns true, for example on BufferedInputStream.

7. Common Mistakes and Best Practices

  • Comparing read() with a byte. Store the result in an int; a byte cannot tell the value 255 from -1.
  • Calling readAllBytes() on large data. It loads everything into memory; process large streams in chunks.
  • Not closing the stream. Use try-with-resources so file handles and sockets are released.
  • Writing your own copy loop. Since Java 9, transferTo() does it for you.

8. Java Version Improvements and Java 25 Updates

Java versionChange
Java 1.0InputStream with read(), skip(), available(), mark() and reset().
Java 5 and 7Implements Closeable (Java 5), and through it AutoCloseable for try-with-resources (Java 7).
Java 9readAllBytes(), readNBytes(byte[], int, int) and transferTo().
Java 11readNBytes(int) and nullInputStream().
Java 12skipNBytes().
Java 25No new methods; everything above is standard.

9. Summary

  • InputStream is the abstract base class of every byte input stream.
  • Its only abstract method is read(), which returns 0–255 or -1.
  • Code that accepts an InputStream works with files, memory, networks and more.
  • Use the return value of read(byte[]); reads can be partial.
  • Prefer readNBytes(), readAllBytes() and transferTo() over manual loops where they fit.

Related Tutorials

10. Official Java Documentation References