How to serialize an object to a byte array?

try {
//init
 Mb TestClass = new TestClass("private string", 1111);
 mb.publicString = "public string";
 mb.publicInt = 123;

//write
 StringBuffer str = new StringBuffer();

 OutputStream out = new OutputStream() {
@Override
 public void write(int b) throws IOException {
str.append((char)b);
}
};

 ObjectOutputStream oos = new ObjectOutputStream(out);
oos.writeObject(mb);
oos.close();

//read
 int i = 0;
 InputStream in = new InputStream() {
@Override
 public int read() throws IOException {
 return str.charAt(i);
}
};

 ObjectInputStream ois = new ObjectInputStream(in);
 TestClass result = (TestClass) ois.the readObject();
ois.close();

System.out.println(result.toString());

 } catch (FileNotFoundException e) {
e.printStackTrace();
 } catch (IOException e) {
e.printStackTrace();
 } catch (ClassNotFoundException e) {
e.printStackTrace();
 }


Get the error
java.io.StreamCorruptedException: invalid stream header: ACACACAC
on the line:
ObjectInputStream ois = new ObjectInputStream(in);

Perhaps I should not use with flows and it can be easier
June 14th 19 at 20:58
1 answer
June 14th 19 at 21:00
Solution
but the stream of bytes is not a string!
then need to something originally? maybe gson is quite?!
How uncomfortable, even ashamed)
Yes, I understand that it is not a string, but I needed to verify (I fell behind quite from Java). To work with the byte representation found a good module: 'org.apache.commons:commons-lang3:3.5'.

But help to understand such question: why when I open the save file (in a text editor), I show:
sr TestClassB_INI
privateIntI publicIntL
privateStringtLjava/lang/String;LpublicStringq~xpW{tprivate stringt
public string

when taking a byte array, I show only the first and last lines:
sr TestClassB_INI
public string
- lavon.Turn commented on June 14th 19 at 21:03

Find more questions by tags Java