00:00

ByteArrayInputStream Class in Java: Reading Bytes from Memory

Last updated:

Many Java APIs read data from an InputStream. But what if the data is already in memory, for example a message received over the network or test data in a unit test? ByteArrayInputStream wraps a byte array so that any stream-based code can read it, without creating a file.

This tutorial covers the class, its constructors and methods, and two practical examples.

1. What Is ByteArrayInputStream in Java?

ByteArrayInputStream is a subclass of InputStream whose source is a byte[] in memory. It keeps a position in the array and returns the bytes in order. It has been part of Java since version 1.0.

2. ByteArrayInputStream Class Hierarchy

ByteArrayInputStream class hierarchyByteArrayInputStream extends the abstract class InputStream, which extends Object, and implements Closeable and AutoCloseable. It reads bytes from a byte array and is typically used in unit tests, for parsing received data and for in-memory processing.ObjectextendsInputStreamabstract classextendsByteArrayInputStreamreads bytes from a byte[]CloseableAutoCloseableimplementsTypical usesunit testsparsing received datain-memory processing

Swipe sideways to see the whole diagram.

3. Constructors of ByteArrayInputStream

ConstructorDescription
ByteArrayInputStream(byte[] buf)Reads the whole array.
ByteArrayInputStream(byte[] buf, int offset, int length)Reads length bytes starting at index offset.

The array is not copied: the stream reads the array you pass in.

4. Commonly Used Methods

MethodDescription
int read()Next byte (0–255), or -1 at the end of the array.
int read(byte[] b, int off, int len)Copies up to len bytes into b.
int readNBytes(byte[] b, int off, int len)Like read, but declared without IOException in this class.
byte[] readAllBytes()Returns the remaining bytes, without IOException.
int available()The exact number of bytes left.
void mark(int) / void reset()Remember a position and return to it; always supported.
void close()Has no effect; the stream can still be used afterwards.

5. Example: Testing Code Without Files

An inventory service totals quantities read from an InputStream. In a unit test, a ByteArrayInputStream supplies sample data, so the test needs no files.

ParserTest.java
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;

public class ParserTest {

    // Production code: reads "product,quantity" lines from any InputStream
    static int totalQuantity(InputStream in) throws IOException {
        int total = 0;
        try (BufferedReader reader = new BufferedReader(new InputStreamReader(in, StandardCharsets.UTF_8))) {
            String line;
            while ((line = reader.readLine()) != null) {
                total += Integer.parseInt(line.split(",")[1].trim());
            }
        }
        return total;
    }

    public static void main(String[] args) throws IOException {
        // Test data lives in memory: no temporary files to create or delete
        String orders = "pens, 12\nnotebooks, 5\nmarkers, 8\n";
        InputStream fake = new ByteArrayInputStream(orders.getBytes(StandardCharsets.UTF_8));

        int total = totalQuantity(fake);
        System.out.println("Total quantity: " + total);
        System.out.println(total == 25 ? "TEST PASSED" : "TEST FAILED");
    }
}
Output
Total quantity: 25
TEST PASSED

How the code works

  1. totalQuantity() is written against InputStream, so production code can pass a file or network stream.
  2. The test turns a string into UTF-8 bytes and wraps them in a ByteArrayInputStream.
  3. The method reads the three lines and returns 25, so the test passes. Nothing has to be cleaned up afterwards.

6. Example: Reading Part of a Byte Array

A device sends packets with a 4-byte header followed by a payload. The second constructor reads just the payload, without copying the array.

PacketSlice.java
import java.io.ByteArrayInputStream;
import java.nio.charset.StandardCharsets;

public class PacketSlice {
    public static void main(String[] args) {
        // A received packet: 4-byte header "HDR:" followed by the payload
        byte[] packet = "HDR:temperature=23.5".getBytes(StandardCharsets.US_ASCII);

        // Read only the payload: start at index 4, take the rest
        ByteArrayInputStream payload = new ByteArrayInputStream(packet, 4, packet.length - 4);
        System.out.println("Bytes available: " + payload.available());

        payload.mark(0);                                  // the argument is ignored by this class
        byte[] first = new byte[11];
        int n = payload.readNBytes(first, 0, first.length);   // no IOException for byte arrays
        String key = new String(first, 0, n, StandardCharsets.US_ASCII);
        payload.reset();                                  // back to the start of the payload
        String whole = new String(payload.readAllBytes(), StandardCharsets.US_ASCII);

        System.out.println("Key:   " + key);
        System.out.println("Whole: " + whole);
    }
}
Output
Bytes available: 16
Key:   temperature
Whole: temperature=23.5

How the code works

  1. new ByteArrayInputStream(packet, 4, packet.length - 4) starts after the header, so available() reports the 16 payload bytes.
  2. readNBytes(first, 0, first.length) reads the 11-byte key. This overload declares no IOException, unlike the inherited readNBytes(int).
  3. reset() returns to the marked position, the start of the payload, so readAllBytes() returns all of it.

7. Important Features

  • No IOException is thrown by its own reading methods, because nothing can fail in memory.
  • mark() and reset() are always supported; the mark() argument has no meaning here.
  • Calling close() is harmless but unnecessary; it releases nothing.

8. Common Mistakes and Best Practices

  • Changing the array while reading. The stream reads the original array, so later changes are visible to it.
  • Using it for very large data. The whole array must fit in memory; stream large data from a file instead.
  • Forgetting the charset when converting text. Use getBytes(StandardCharsets.UTF_8).
  • Creating temporary files in unit tests. A ByteArrayInputStream is simpler and faster.

9. Java Version Improvements and Java 25 Updates

Java versionChange
Java 1.0ByteArrayInputStream with both constructors.
Java 9InputStream gains readAllBytes(), readNBytes() and transferTo(); this class overrides them to work directly on the array.
Java 25No changes; the class is fully supported.

10. Summary

  • ByteArrayInputStream lets stream-based code read a byte[] in memory.
  • It is ideal for unit tests and for parsing data you already have.
  • The offset and length constructor reads part of an array without copying it.
  • mark()/reset() always work, and close() has no effect.

Related Tutorials

11. Official Java Documentation References