Joel Pou Joel Pou - 2 years ago 206
Android Question

Java write bytes from Bytebuffer to File in byte format

I'm building a custom file creater app with Android. I'm attempting to write the contents of a Bytebuffer, which are String members from a custom class I created, to a file in byte type. However, whenever I do so I get the contents of the file in String format. I've tried several alternatives such as using get method, BufferedOutputStream class, ByteArrayOutputStream class, DataOutputStream, Filechannel class, etc. Here is my code:

ByteBuffer byteBuffer = ByteBuffer.allocate(totalSize);



byte[] bablock = new byte[byteBuffer.remaining()];

BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(idHeader));

} catch (FileNotFoundException e) {
} catch (IOException e) {

Keep getting the following contents on my idHeader file:


Which is all of my Strings concatenated. What I would like to do is write the same contents as bytes to the file, not as a human-readable string. What I am missing here? Any help is appreciated.

Answer Source

So instead of building Strings and getting byte arrays from them and putting those to the ByteBuffer and writing that to the file, you need to write the data directly. I would get rid of the ByteBuffer and use the various APIs of DataOutputStream to write the individual bytes or ints or whatever.

It being entirely unclear whether you want to write 12345678 as 8 bytes or as a 4-byte integer, for example, it is impossible to help you further without clarification.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download