Can we append multiple data into a bufferedoutputStream?

315 views Asked by At

I have data from 3 files in a ByteArrayOutputStream variable. But when I try to pass it on through BufferedOutputStream, it only sends the data for the last file.

byte [] finalData = new byte[64000];
finalData = outputStream.toByteArray();     
output.write(finalData, 0, finalData.length);

It is overwriting the previous data for 2 files somehow.

1

There are 1 answers

2
Peter Lawrey On

ByteArrayOutputStream variable. But when I try to pass it on through BufferedOutputStream

I suggest writing the files directly to the BufferedOutputStream to reduce memory copies.

it only sends the data for the last file.

Most likely to are opening and closing the file repeatedly, writing over the file each time. You could append to the file, but the most efficient way is to write directly to the file.

Note: to read the file you need some way of determining where a file starts and ends. One approach is to write an index to the end of the file (e.g. as ZIP does) or write a second file which has the offsets, or write the length to the start of the message appended. If it's a text format you might have another way to determine where one starts/ends.