0

I am using message api to send messages between a smart phone and a smart watch. As it can send only byte arrays as data, I would like to convert an object into byte array while sending and reverse the conversion while receiving.

I have used the below code which I got from internet. But I am getting java.io.NotSerializableException. Is there any better way to do it?

My object will have a string value and an android bundle. Both needs to be sent from one device and received at the other end.

public static byte[] toByteArray(Object obj) throws IOException {
        byte[] bytes = null;
        ByteArrayOutputStream bos = null;
        ObjectOutputStream oos = null;
        try {
            bos = new ByteArrayOutputStream();
            oos = new ObjectOutputStream(bos);
            oos.writeObject(obj);
            oos.flush();
            bytes = bos.toByteArray();
        } finally {
            if (oos != null) {
                oos.close();
            }
            if (bos != null) {
                bos.close();
            }
        }
        return bytes;
    }

public static Event toObject(byte[] bytes) throws IOException, ClassNotFoundException {
        Event obj = null;
        ByteArrayInputStream bis = null;
        ObjectInputStream ois = null;
        try {
            bis = new ByteArrayInputStream(bytes);
            ois = new ObjectInputStream(bis);
            obj = (Event) ois.readObject();
        } finally {
            if (bis != null) {
                bis.close();
            }
            if (ois != null) {
                ois.close();
            }
        }
        return obj;
    }
NewOne
  • 401
  • 5
  • 19
  • Is your object Serializable? Said that, why not make your methods receive `Serializable obj` instead? – Budius May 20 '16 at 10:32
  • look here: http://stackoverflow.com/questions/2836646/java-serializable-object-to-byte-array – Konstantin May 20 '16 at 10:54
  • Thanks a lot for the link. Using ApacheUtils worked for me: To Serialize: byte[] data = SerializationUtils.serialize(yourObject); deserialize: YourObject yourObject = (YourObject) SerializationUtils.deserialize(byte[] data) – NewOne May 23 '16 at 07:39

1 Answers1

0
 public void toByteArray(Object obj) throws IOException {
    FileOutputStream outputstream = new FileOutputStream(new File("/storage/emulated/0/Download/your_file.bin"));
    outputstream.write((byte[]) obj);
    Log.i("...","Done");
    outputstream.close();
}

Try this may it'll work for you, it will store your file in downloads folder in your smartphone.

BOUTERBIAT Oualid
  • 1,494
  • 13
  • 15