Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Java

Serializable Sample Code

Hi,

After going through most of the Java course, I created an application for making a meal plan. I am trying to save my data to a file using Serialization, but I keep getting an IOException thrown. I don't know what I'm doing wrong. Here is some sample code (just trying to save and import something right now):

Demo object = new Demo(1, "geeksforgeeks"); String filename = "file.ser";

    // Serialization 
    try
    {   
        //Saving of object in a file
        FileOutputStream file = new FileOutputStream(filename);
        ObjectOutputStream out = new ObjectOutputStream(file);

        // Method for serialization of object
        out.writeObject(object);

        out.close();
        file.close();

        System.out.println("Object has been serialized");

    }

    catch(IOException ex)
    {
        System.out.println("IOException is caught");
    }


    Demo object1 = null;

    // Deserialization
    try
    {   
        // Reading the object from a file
        FileInputStream file = new FileInputStream(filename);
        ObjectInputStream in = new ObjectInputStream(file);

        // Method for deserialization of object
        object1 = (Demo)in.readObject();

        in.close();
        file.close();

        System.out.println("Object has been deserialized ");
        System.out.println("a = " + object1.a);
        System.out.println("b = " + object1.b);
    }

    catch(IOException ex)
    {
        System.out.println("IOException is caught");
    }

    catch(ClassNotFoundException ex)
    {
        System.out.println("ClassNotFoundException is caught");
    }

}

Can you post the complete stacktrace? An IOException could be a number of things that have nothing to do with your code: the file might not be accessible, there might be an encoding problem, etc.