Java – ByteArrayOutputStream.toByteArray() or read from a stream?

ByteArrayOutputStream.toByteArray() or read from a stream?… here is a solution to the problem.

ByteArrayOutputStream.toByteArray() or read from a stream?

In my Android application, I store my data in ByteArrayOutputStream (currently around 1 MB maximum), which I want to pass to DataOutputStream.

The most obvious method is, of course, to call:

dataOS.write(byteArrayOS.toByteArray())

But there’s a more complex (but probably more effective) approach:

ByteArrayInputStream rdr = new ByteArrayInputStream(byteArrayOS.toByteArray());
int read;
byte[] buffer = new byte[1024];
while ((read = rdr.read(buffer)) > 0){
    dataOS.write(buffer,0,read);
}

The amount of data stored in ByteArrayOutputStream may grow in the future. Which of the two is more efficient? Write a lot of data at once or sequentially?

Update:

DataOutputStream is used to write over the network (it is created via UrlConnection.getOutputStream()).

Solution

The first one is more efficient because instead of creating N 1024-byte blocks and sending them separately to the DataOutputStream, it sends the entire byte array at once.

Anyway, you already have the entire byte array in memory. It is useful to read and write as blocks from streams that do not read from byte arrays in memory, such as file or socket input streams, because this avoids putting the entire byte array in memory.

Related Problems and Solutions