1

I have a byte[] with 3 different objects. How can I read from the byte[] and separate the objects?

My code:

  public byte[] toByteArray() {

            byte[] bytes;
            byte[] sb = start.toString().getBytes();
            byte[] gb = goal.toString().getBytes();
            byte[] mb = gameBoard.toString().getBytes();
            bytes = new byte[sb.length + gb.length + mb.length];
            System.arraycopy(sb, 0, bytes, 0, sb.length);
            System.arraycopy(gb, 0, bytes, sb.length, gb.length);
            System.arraycopy(mb, 0, bytes, gb.length, mb.length);
            return bytes;

        }
Micha Wiedenmann
  • 19,979
  • 21
  • 92
  • 137
Guy Ben-Shahar
  • 231
  • 1
  • 11

3 Answers3

3

Seems like you are talking about Java not JavaScript.

I recommend you to have a look at binary serialization which I guess is what you are looking for: Saving to binary/serialization java

Community
  • 1
  • 1
Timo Denk
  • 575
  • 1
  • 6
  • 21
2

If you store your data like this, it will be a very difficult task to read them.

I recommend using some build-in object-to-byte[] (and back) conversions like Serializable.

Also, to store several object inside one byte[] array, have a look into ObjectOutputStream

kajacx
  • 12,361
  • 5
  • 43
  • 70
1

First of all you will need an actual byte[] where stuff can be read from. There are some issues about what you are trying.

  • toString() usually is not fit to get some data you can reconstruct the object from. It might work with an integer, get a bit messed up with floating point, and be outright impossible with complex objects which only tell about their type and id. (as Davide comment pointed)
  • There are no cues about where one object starts and ends. Even worse: you might have messed up the start position of 3rd object.

The JRE has a built-in serialization. Other people use XML or JSON when they need to interact with something else. You might even implement your own flavor of java.text.Format which is able to format and parse your objects. Pick your poison.

Javier
  • 678
  • 5
  • 17