I have understood the Bytearrayoutputstream api. My question is a bit different. I am interested in understanding what is the real life scenario where I would use it ? For all reasons, I seem to only feel FileIO is useful, I am trying to understand the use-case of Bytearrayoutputstream.
-
1I use it in testing a lot. Particularly where I am testing code that handles binary data. – BevynQ Mar 10 '14 at 02:30
-
The 'practical use' is when you want to write to a byte array instead of a file, or a socket, or ... It happens all the time. The real question is why you think that isn't useful. – user207421 Mar 10 '14 at 02:51
2 Answers
If you're generating transient data, it's much nicer to use a byte array to store the data instead of worrying about all of the cases in which you might have to clean up the file later. File.deleteOnExit()
leaks memory and fails in the event of a system crash. For temporary data, it's nice to benefit from automatic garbage collection.
In the context of clustered web applications with session replication it also allows you to share the data in the user session. If the user's session is moved to another node, the data is still available to the web application. This isn't generally the case with files on disk.

- 5,691
- 1
- 30
- 41
We could use ByteArrayOutputStream
to calculate the rough Object Memory size
private int getBytesSize(Object o) {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutput out = null;
try {
out = new ObjectOutputStream(bos);
out.writeObject(o);
return bos.toByteArray().size;
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (out != null) {
out.close();
}
} catch (IOException ex) {
// ignore close exception
}
try {
bos.close();
} catch (IOException ex) {
// ignore close exception
}
}
return 0;
}
Credit goes to the original post as https://stackoverflow.com/a/38188384

- 53,639
- 54
- 212
- 474