ByteArrayInputStream Class in Java: Reading Bytes from Memory
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
Swipe sideways to see the whole diagram.
3. Constructors of ByteArrayInputStream
| Constructor | Description |
|---|---|
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
| Method | Description |
|---|---|
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.
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");
}
}
Total quantity: 25 TEST PASSED
How the code works
totalQuantity()is written againstInputStream, so production code can pass a file or network stream.- The test turns a string into UTF-8 bytes and wraps them in a
ByteArrayInputStream. - 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.
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);
}
}
Bytes available: 16 Key: temperature Whole: temperature=23.5
How the code works
new ByteArrayInputStream(packet, 4, packet.length - 4)starts after the header, soavailable()reports the 16 payload bytes.readNBytes(first, 0, first.length)reads the 11-byte key. This overload declares noIOException, unlike the inheritedreadNBytes(int).reset()returns to the marked position, the start of the payload, soreadAllBytes()returns all of it.
7. Important Features
- No
IOExceptionis thrown by its own reading methods, because nothing can fail in memory. mark()andreset()are always supported; themark()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
ByteArrayInputStreamis simpler and faster.
9. Java Version Improvements and Java 25 Updates
| Java version | Change |
|---|---|
| Java 1.0 | ByteArrayInputStream with both constructors. |
| Java 9 | InputStream gains readAllBytes(), readNBytes() and transferTo(); this class overrides them to work directly on the array. |
| Java 25 | No changes; the class is fully supported. |
10. Summary
ByteArrayInputStreamlets stream-based code read abyte[]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, andclose()has no effect.