Aloyweesious
Aloyweesious

Reputation: 41

Arraylist of byte[] Java

I'm wondering if it is possible for me to add multiple byte[] of a file into an arraylist and later on write the btye[] inside back to a file.

Sorry for being vague, this is my first time posting below is a segment of my code. the output file seem to be bigger then the original file and i cant seem to figure out why

ArrayList<byte[]> tempStorage = new ArrayList<byte[]>();
byte[] byteArray;

while (n < length && n != -1)
{
    byteArray = new byte[960];
    n = in.read(byteArray, 0, 960);
    tempStorage.add(byteArray);
    count++;
}

for (byte[] temp: tempStorage) {
    fileOuputStream.write(temp);
}
fileOuputStream.close();

Upvotes: 0

Views: 6308

Answers (1)

Pshemo
Pshemo

Reputation: 124215

Lets say that size of your array is 4 and size of file is 6. You read first 4 bytes, place it in array and store that array in list. Then you are reading that last 2 bytes (since size was 6) and store it in array which size is 4. This means that some part of that last array will be empty and should be ignored.

But in your

for (byte[] temp: tempStorage) {
    fileOuputStream.write(temp);
}

you are writing last array entirely, including part which should be ignored (so you will write 4 bytes instead of 2 which will make your file bigger).

So for last temp you should use write method which will describe how many bytes from that array we want to use (you have that information in n variable since you get it in n = in.read(byteArray, 0, 960);).

So for last temp try something more like fileOuputStream.write(temp,0,n)

Upvotes: 4

Related Questions