Question

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
}
Was it helpful?

Solution

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]

OTHER TIPS

The following will read all the data from FileInputStream into byte array:

FileInputStream input = new FileInputStream (file);
ByteArrayOutputStream output = new ByteArrayOutputStream ();
byte [] buffer = new byte [65536];
int l;
while ((l = input.read (buffer)) > 0)
    output.write (buffer, 0, l);
input.close ();
output.close ();
byte [] data = output.toByteArray ();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top