0

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();
2
  • 5
    why don't you try and see it yourself? Commented Oct 12, 2015 at 13:56
  • 2
    Please try before you ask, but if you have a problem on your test, you can ask! Commented Oct 12, 2015 at 14:00

1 Answer 1

4

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)

Sign up to request clarification or add additional context in comments.

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.