How to store primitives using BufferedOutputStream

91 views Asked by At

Hello everyone I'm in my second semester of CS and we are on the subject of file IO using InputStreams and OutputStreams, everything was relatively simple until this subject for me. I am a little confused with the BufferedOutputStream class. I understand that it stores data in a buffer of the specified size, then writes it all at once to be more efficient than a byte by byte stream. What I do not understand is that, unlike DataInputStream, which has methods to write specific primitives, I can only write byte arrays. How would I store primitives like int, long, double, etc.. using the BufferedOutputStream. Thank you guys in advance!

2

There are 2 answers

0
Shanu Gupta On

You could use guava library for converting primitves to byteArray. It has pretty sweet syntax:

byte[] bytearray = Ints.toByteArray(201);

where 201 is the primitive integer you wish to use. Since now you have byteArray you can easily use it in BufferedOutputStream.

8
user207421 On

Wrap a DataOutputStream around it.