CKTIS / Java
ByteArrayInputStream — reading bytes from an array
ByteArrayInputStream exposes a byte array as an input stream. Its close() does not prevent further reads.
Version: Java SE 21; repository runtime, production runtime not attested
Syntax
public ByteArrayInputStream(byte[] buf)
public ByteArrayInputStream(byte[] buf, int offset, int length)
public void close() throws IOExceptionjava.io.ByteArrayInputStream extends InputStream to read bytes from memory. Its constructor accepts an entire array or a range defined by offset and length. It does not copy the array: changes to its contents can affect later reads.
read() returns an int from 0–255, or -1 at end of stream. available() reports the remaining byte count.
mark(int readAheadLimit) saves the position; reset() returns to it. The readAheadLimit argument is required even though this class ignores its value. The initial mark points to the start of the selected range.
ByteArrayInputStream.close() has no effect; reading and reset() still work. However, its declaration includes throws IOException, so callers must handle or declare the exception. Do not generalize this behavior to other streams.
Examples
import java.io.ByteArrayInputStream;
import java.io.IOException;
public class Main {
public static void main(String[] args) throws IOException {
byte[] data = {10, (byte) 255};
ByteArrayInputStream input = new ByteArrayInputStream(data);
System.out.println(input.read());
input.close();
System.out.println(input.read());
System.out.println(input.read());
input.reset();
System.out.println(input.read());
}
}Result
10 255 -1 10
The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.