Serialize object to a byte array

Hi,

Can someone show me how to serialize a simple class to a byte array? Something like:

class Test implements Serializable {
    String str = "hello";
}

void main()
{
    Test t = new Test();
    ByteArray b = new ByteArray();
    t.toBytearray(b);

    // later on just recreate the object from the byte array
    Test t2 = new Test();
    t2.fromByteArray(b);
}

Thanks
DJ_AM_JuiceboxAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Bart CremersJava ArchitectCommented:

import java.io.*;
 
public class Test implements Serializable {
    String str = "hello";
 
    public static void main(String[] args) throws IOException, ClassNotFoundException {
        Test t = new Test();
 
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ObjectOutputStream oos = new ObjectOutputStream(baos);
        oos.writeObject(t);
 
        byte[] byteArray = baos.toByteArray();
 
        // later on just recreate the object from the byte array
        ByteArrayInputStream bais = new ByteArrayInputStream(byteArray);
        ObjectInputStream ois = new ObjectInputStream(bais);
 
        Test t2 = (Test) ois.readObject();
 
        System.out.println("t2.str = " + t2.str);
    }
}

Open in new window

0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
drazen_nikolicCommented:
The proposed solution is OK.
Anyhow, last year I have found one interesting post with the class enabling to easy serialize/deserialize JAVA objects (actually the list of objects).

Check next URL (seek for the last post):
http://forum.java.sun.com/thread.jspa?threadID=5226234&tstart=0

You have a very good example there. Hope this helps.
0
DJ_AM_JuiceboxAuthor Commented:
Hmm not having any luck - I get an IOException as soon as I try to write. Here's the sample I had put together, pretty much exactly like yours, I must be missing something:

public class Main
{
    public class Test1 implements Serializable {
        public static final long serialVersionUID = 0;
        String m_str = "hello";
        public Test1() {}
    }
   
    public static void main(String[] args)
    {
        Main m = new Main();
        m.test();
    }
      
    public void test()
    {
        // Serialize first.
        Test1 t1 = new Test1();
        System.out.println("Test1: " + t1.toString());
              
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        try {
                ObjectOutputStream oos = new ObjectOutputStream(baos);
                oos.writeObject(t1);


Yeah right there it throws an IOException, on writeObject().... any idea what I'm missing?

Thanks
0
CompTIA Cloud+

The CompTIA Cloud+ Basic training course will teach you about cloud concepts and models, data storage, networking, and network infrastructure.

Bart CremersJava ArchitectCommented:
Could you provide more info on the error message?
0
DJ_AM_JuiceboxAuthor Commented:
It is pretty useless to me, it just says:

    "Main"

I use it like:

try {
    ObjectOutputStream oos = new ObjectOutputStream(baos);
    oos.writeObject(t1);
}
catch (IOException e) {
    System.out.println(e.getMessage());
}
0
Bart CremersJava ArchitectCommented:
Seeing the full stack trace might help out in finding the problem.
0
DJ_AM_JuiceboxAuthor Commented:
How do you do a full stack trace? I just get:

    [Ljava.lang.StackTraceElement;@7bb290

after calling:

    System.out.println(e.getStackTrace());
0
Bart CremersJava ArchitectCommented:
Just do e.printStackTrace();
0
DJ_AM_JuiceboxAuthor Commented:
ok here it is:

java.io.NotSerializableException: Main
      at java.io.ObjectOutputStream.writeObject0(Unknown Source)
      at java.io.ObjectOutputStream.defaultWriteFields(Unknown Source)
      at java.io.ObjectOutputStream.writeSerialData(Unknown Source)
      at java.io.ObjectOutputStream.writeOrdinaryObject(Unknown Source)
      at java.io.ObjectOutputStream.writeObject0(Unknown Source)
      at java.io.ObjectOutputStream.writeObject(Unknown Source)
      at Main.test(Main.java:40)
      at Main.main(Main.java:26)
0
DJ_AM_JuiceboxAuthor Commented:
it appears it can't work because my definition of Test1 is inside another class - so only top level classes can be serialized I guess. How annoying!
0
Bart CremersJava ArchitectCommented:
You could make the Test1 class static or make Main serializable as well. The Main class will be an anonymous member of the subclass, so it needs to be serializable as well.
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Java

From novice to tech pro — start learning today.