InputStream Class in Java: Methods and Examples
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.
public abstract class InputStream implements Closeable
2. InputStream Class Hierarchy
Swipe sideways to see the whole diagram.
3. Methods of the InputStream Class
| Method | Returns | Description |
|---|---|---|
read() | int | Next byte (0–255), or -1 at the end. |
read(byte[] b, int off, int len) | int | Reads 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 / void | Skips bytes; skipNBytes (Java 12) skips exactly n or throws EOFException. |
available() | int | An estimate of bytes readable without blocking; not the total size. |
mark(int) / reset() | void | Remember a position and return to it, if markSupported() is true. |
transferTo(OutputStream out) | long | Copies all remaining bytes and returns the count (Java 9). |
nullInputStream() | InputStream | A static factory for an empty stream (Java 11). |
close() | void | Releases 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.
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);
}
}
Memory checksum: 08092a81 File checksum: 08092a81 Same content: true
How the code works
crc32()depends only on the abstractInputStreamtype, so it never needs to know where the bytes come from.read(buffer)returns how many bytes were actually read, and only those bytes are passed toCRC32.update().ByteArrayInputStreamandFiles.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.
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));
}
}
}
Type: PING Body: server-07 is alive End of stream: true
How the code works
readNBytes(4)reads exactly the type field, without a manual loop.skipNBytes(2)discards the reserved bytes and would throwEOFExceptionif the message were too short.readAllBytes()returns the rest of the message, after whichread()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()andreset()work only whenmarkSupported()returnstrue, for example onBufferedInputStream.
7. Common Mistakes and Best Practices
- Comparing
read()with abyte. Store the result in anint; abytecannot 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 version | Change |
|---|---|
| Java 1.0 | InputStream with read(), skip(), available(), mark() and reset(). |
| Java 5 and 7 | Implements Closeable (Java 5), and through it AutoCloseable for try-with-resources (Java 7). |
| Java 9 | readAllBytes(), readNBytes(byte[], int, int) and transferTo(). |
| Java 11 | readNBytes(int) and nullInputStream(). |
| Java 12 | skipNBytes(). |
| Java 25 | No new methods; everything above is standard. |
9. Summary
InputStreamis 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
InputStreamworks with files, memory, networks and more. - Use the return value of
read(byte[]); reads can be partial. - Prefer
readNBytes(),readAllBytes()andtransferTo()over manual loops where they fit.
Related Tutorials
- Byte Stream in Java
- OutputStream Class in Java
- FileInputStream Class in Java
- BufferedInputStream Class in Java