Reading InputStream bytes and writing to ByteArrayOutputStream

I have code block to read mentioned number of bytes from an InputStream and return a byte[] using ByteArrayOutputStream. When I'm writing that byte[] array to a file, resultant file on the filesystem seems broken. Can anyone help me find out problem in the below code block.

public byte[] readWrite(long bytes, InputStream in) throws IOException {
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    int maxReadBufferSize = 8 * 1024; //8KB
    long numReads = bytes/maxReadBufferSize;
    long numRemainingRead = bytes % maxReadBufferSize;
    for(int i=0; i<numReads; i++) {
        byte bufr[] = new byte[maxReadBufferSize];
        int val = in.read(bufr, 0, bufr.length);
        if(val != -1) {
            bos.write(bufr);
        }
    }
    if(numRemainingRead > 0) {
        byte bufr[] = new byte[(int)numRemainingRead];
        int val = in.read(bufr, 0, bufr.length);
        if(val != -1) {
            bos.write(bufr);
        }
    }
    return bos.toByteArray();
}

Upvotes: 3

Views: 657

Answers (1)

Akash Yadav
Akash Yadav

Reputation: 105

My understanding of the problem statement

Read bytes number of bytes from the given InputStream in a ByteArrayOutputStream.
Finally, return a byte array.

Key observations

  • A lot of work is done to make sure bytes are read in chunks of 8KB.
    Also, the last remaining chunk of odd size is read separately.

  • A lot of work is also done to make sure we are reading from the correct offset.

My views

  • Unless we are reading a very large file (>10MB) I don't see a valid reason for reading in chunks of 8KB.

  • Let Java libraries do all the hard work of maintaining offset and making sure we don't read outside limits. Eg: We don't have to give offset, simply do inputStream.read(b) over and over, the next byte array of size b.length will be read. Similarly, we can simply write to outputStream.

Code

public byte[] readWrite(long bytes, InputStream in) throws IOException {
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    byte[] buffer = new byte[(int)bytes];

    is.read(buffer);
    bos.write(buffer);

    return bos.toByteArray();
}

References

About InputStreams
Byte Array to Human Readable Format

Upvotes: 1

Related Questions