sabarirajan
sabarirajan

Reputation: 177

How to serialize Java object - converting object as an InputStream

If I write my code like this, it gives an error "File not found access denied ......"

public class ImplRegistration implements IRegistration {
 @Override
    public boolean newRegistration(Registration_BE reg_be) {
        FileOutputStream fos = new FileOutputStream("serial.ser");
        ObjectOutputStream oos = new ObjectOutputStream(fos);
        oos.writeObject(reg_be);
    }
}

For security reasons, I changed the fourth line of the code to this:

FileOutputStream fos = new FileOutputStream("f://serial.ser");

But then it showed the exception java.io.NotSerializableException: java.io.ByteArrayInputStream.

How can I serialize the object?

Upvotes: 1

Views: 5227

Answers (2)

Houser
Houser

Reputation: 41

The serialization operation in this case is failing because, as Ted Hopp states in the comments above, the class you are attempting to serialize contains a non-transient (and non-serializable) ByteArrayInputStream object. To remedy this and make the Registration_BE class serializable, you can mark this field as transient:

class Registration_BE {
  // rest of class

  private transient ByteArrayInputStream bais = null;

  // rest of class
}

This will cause it to be omitted from the serialization process of Registration_BE, but will also cause it to be uninitialized when the object is deserialized on the other end.

If you wish to initialize the ByteArrayInputStream after deserialization, you may want to consider writing custom writeObject / readObject methods for the Registration_BE class. There are many tutorials on custom serialization available on Google. The information in this thread might help to get you started:

Uses of readObject/writeObject in Serialization

Upvotes: 1

Ruchira Gayan Ranaweera
Ruchira Gayan Ranaweera

Reputation: 35557

If you try to access file in your operation system(OS) partition, it will give access denied error.

Upvotes: 0

Related Questions