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);
byteBuffer.put(hm.getDocID().getBytes());
byteBuffer.put(hm.getFextension().getBytes());
byteBuffer.put(hm.getMagic().getBytes());
byteBuffer.put(hm.getFversion().getBytes());
byteBuffer.put(hm.getFsize().getBytes());
byteBuffer.flip();
byte[] bablock = new byte[byteBuffer.remaining()];
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(idHeader));
bos.write(bablock);
bos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Keep getting the following contents on my idHeader file:
12345678-1234-1234-1234-123456789abcjpgIDF1.00000166178
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.
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.