java - How to (de)serialize correctly to a byte-array using a ObjectOutputStream & ObjectInputStream? -


i aware objectoutputstream/objectinputstream uses headers , not proper use-case. anyway need wrap data using interfaces datainput , dataoutput.

import java.util.*; import java.lang.*; import java.io.*;  class ideone {     public static void main (string[] args) throws java.lang.exception     {         byte[] array = serialize("test");         string deserialized = deserialize(array);          system.out.println(deserialized);     }      private static byte[] serialize(string test) {         bytearrayoutputstream bytearrayoutputstream = new bytearrayoutputstream();          try {             objectoutputstream objectoutputstream = new objectoutputstream(bytearrayoutputstream);              objectoutputstream.writeutf(test);              bytearrayoutputstream.close();         } catch (ioexception e) {             e.printstacktrace();         }          return bytearrayoutputstream.tobytearray();     }      private static string deserialize(byte[] array) {         string temp = null;          try {             objectinputstream objectinputstream = new objectinputstream(new bytearrayinputstream(array));              temp = objectinputstream.readutf();              objectinputstream.close();         } catch (ioexception e) {             e.printstacktrace();         }          return temp;     } } 

i don't how working. right, problem headers currently?

you should call objectoutputstream.flush(); before closing bytearrayoutputstream.

objectoutputstream have internal buffer got beginning of string in byte array.


Comments

Popular posts from this blog

python - Selenium remoteWebDriver (& SauceLabs) Firefox moseMoveTo action exception -

html - How to custom Bootstrap grid height? -

transpose - Maple isnt executing function but prints function term -