Search code examples
javaarraysserializationbytearrayoutputstream

How do I store several values in byte array in Java?


So I am currently trying to save and load Data for my Java application. Now i am trying to save all my data in one big byte[] which I can than write to a file using Base64. I've seen something like this before, where you can do writeString(String s) to write a String to a byte[] and use readString() to read the String from the byte[]. I was wondering how exactly this works; How can I write several values to the byte[] and know when one Value ends and another begins. With Integers it would be easy, because they have a fixed size, but Strings are dynamic, so how can I see when the String in the byte[] ends?

I already managed to write data to a byte[] using the ByteBufferOutputStream and now I need to know how I can discriminate the different values. Could I for example insert a 0x0-byte where the String's bytes end to know when to stop reading the byte[]?


Solution

  • Either a 0x00 to indicate end of string or you could store the length of the string first then then data bytes after that.