1

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
}
1
  • 2
    where is the byte array(in your code)? Commented Feb 7, 2013 at 10:18

2 Answers 2

5

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]
Sign up to request clarification or add additional context in comments.

2 Comments

Does that work if the size off the array is odd? You have an even sized array and are reading in 2 bytes. What if the array was 7 bytes long? On the last loop it only reads in one byte?
@AndroidDev Was still working on this while you posted your comment :D See my updated code. BTW: It would also have worked before, but the last chunk would have contained data from the previous read. In any case, you need to check the return value from is.read() to check how many bytes have actually been read, or use the return value from is.available() to see if a whole chunk is still available. There are several possibilities to solve this - probably System.arraycopy() is not the best one ...
1

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 ();

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.