V
V
Vitaly2017-10-01 20:02:31
Java
Vitaly, 2017-10-01 20:02:31

How to serialize an object into an array of bytes?

try {
            //init
            TestClass mb = 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.readObject();
            ois.close();

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

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

I get an error
java.io.StreamCorruptedException: invalid stream header: ACACACAC
on the line: Perhaps I am using threads in vain and this can be done more simply
ObjectInputStream ois = new ObjectInputStream(in);

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
aol-nnov, 2017-10-01
@vitali1995

but a stream of bytes is not a string!
what do you need in the first place? maybe gson is enough?!

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question