Replacing a BufferedInputStream with a byte array in Java

AndroidDev picture AndroidDev · Feb 7, 2013 · Viewed 7.4k times · Source

The following code reads data from a file using a BufferedInputStream and processes it in chuncks. I would like to modify this code so that instead of the data coming from a file through a stream, I would like to have it come from a byte array. I have already read the file's data into a byte array and I want to use this while...loop to process the array data instead of working with the data from the file stream. Not sure how to do it:

FileInputStream in = new FileInputStream(inputFile);
BufferedInputStream origin = new BufferedInputStream(in, BUFFER);

int count;

while ((count = origin.read(data, 0, BUFFER)) != -1)
{
  // Do something
}

Answer

Andreas Fester picture Andreas Fester · Feb 7, 2013

You can use a ByteArrayInputStream to wrap your existing byte array into an InputStream so that you can read from the byte array as from any other InputStream:

byte[] buffer = {1,2,3,4,5};
InputStream is = new ByteArrayInputStream(buffer);

byte[] chunk = new byte[2];
while(is.available() > 0) {
    int count = is.read(chunk);
    if (count == chunk.length) {
        System.out.println(Arrays.toString(chunk));
    } else {
        byte[] rest = new byte[count];
        System.arraycopy(chunk, 0, rest, 0, count);
        System.out.println(Arrays.toString(rest));
    } 
}
Output:
[1, 2]
[3, 4]
[5]