ByteArrayInputStream class
ByteArrayInputStream is an implementation of an InputStream that uses a byte array as the source.
This class has two constructors, each of which requires a byte array to provide the data source:
ByteArrayInputStream(byte array[ ])
- array is the input source.
ByteArrayInputStream(byte array[ ], int start, int numBytes)
- uses a subset of your byte array.
Methods from ByteArrayInputStream
int available()
- Returns the number of remaining bytes that can be read (or skipped over) from this input stream.
void close()
- Closing a ByteArrayInputStream has no effect.
void mark(int readAheadLimit)
- Set the current marked position in the stream.
boolean markSupported()
- If this InputStream supports mark/reset.
int read()
- Reads the next byte of data.
int read(byte[] b, int off, int len)
- Reads up to len bytes of data into an array of bytes from this input stream.
void reset()
- Resets the buffer to the marked position.
long skip(long n)
- Skips n bytes of input from this input stream.
Revised from Open JDK source code
Create ByteArrayInputStream from byte array
import java.io.ByteArrayInputStream;
import java.io.IOException;
public class Main {
public static void main(String args[]) throws IOException {
String tmp = "abcdefghijklmnopqrstuvwxyz";
byte b[] = tmp.getBytes();
ByteArrayInputStream input1 = new ByteArrayInputStream(b);
ByteArrayInputStream input2 = new ByteArrayInputStream(b, 0, 3);
}
}
A ByteArrayInputStream implements both mark( ) and reset( ). The following example uses the reset( ) method to read the same input twice.
import java.io.ByteArrayInputStream;
import java.io.IOException;
public class Main {
public static void main(String args[]) throws IOException {
String tmp = "abc";
byte b[] = tmp.getBytes();
ByteArrayInputStream in = new ByteArrayInputStream(b);
for (int i = 0; i < 2; i++) {
int c;
while ((c = in.read()) != -1) {
if (i == 0) {
System.out.print((char) c);
} else {
System.out.print(Character.toUpperCase((char) c));
}
}
System.out.println();
in.reset();
}
}
}
The following code reads byte array out of ByteArrayInputStream
import java.io.ByteArrayInputStream;
import java.io.IOException;
public class Main {
public static void main(String args[]) throws IOException {
ByteArrayInputStream inStream = new ByteArrayInputStream(("java2s.com").getBytes());
int inBytes = inStream.available();
System.out.println("inStream has " + inBytes + " available bytes");
byte inBuf[] = new byte[inBytes];
int bytesRead = inStream.read(inBuf, 0, inBytes);
System.out.println(bytesRead + " bytes were read");
System.out.println("They are: " + new String(inBuf));
}
}
The output:
inStream has 10 available bytes
10 bytes were read
They are: java2s.com