-2

I am trying to serialize an object with ObjectOutputStream and FileOutputStream, however an error with the class name is being shown.

JFileChooser fc = new JFileChooser();
 NewClientClass AddClient = new NewClientClass(IDNumber.getText(), FirstName.getText(), LastName.getText(), Address.getText(), DateOfBirth.getText(), Profession.getText());
       try {   
        int returnVal = fc.showSaveDialog(null);
        if (returnVal == JFileChooser.APPROVE_OPTION) {
            ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(fc.getSelectedFile().getAbsoluteFile()));
            out.writeObject(AddClient); //the application crashes.
            out.close();
            JOptionPane.showMessageDialog(null, "Successfully Saved");
        }

As you can see I am declaring a new client and getting the data from the text boxes. The data is stored correctly as I checked tru debugging, the only problem is when writing the object to file.

Any help please?

Thanks

1 Answers1

1

Without further details, the most likely culprit is that lack of the implementation of the Serializable interface from NewClientClass:

Serializability of a class is enabled by the class implementing the java.io.Serializable interface. Classes that do not implement this interface will not have any of their state serialized or deserialized. All subtypes of a serializable class are themselves serializable. The serialization interface has no methods or fields and serves only to identify the semantics of being serializable.

EDIT:

Assuming you have something like so:

public class NewClientClass
{
    public NewClientClass (String idNumber, String firstName, String lastName, String address, String dateOfBirth, String profession)
    {
         ...
    }

}

You would just need to make it like so:

public class NewClientClass implements Serializable
{
    public NewClientClass (String idNumber, String firstName, String lastName, String address, String dateOfBirth, String profession)
    {
         ...
    }
}

That should be all you need to do (do not forget to import the package containing that interface). The Serializable interface will mark your class for seriliazation.

Again, you did not mention what exception you are getting, so this is purely speculative.

npinti
  • 51,780
  • 5
  • 72
  • 96