Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

De-serializing objects from a file in Java

I have a file which contains multiple serialized objects of class XYZ. While serializing, the each XYZ object was appended to the file.

Now I need to read each object from the file, and I am able to read only the first object.

Any idea how I can read each object from the file and eventually store it into a List?

like image 947
topgun_ivard Avatar asked Oct 19 '11 19:10

topgun_ivard


People also ask

Which one is the correct method of serializing an object to a file?

The ObjectOutputStream class contains writeObject() method for serializing an Object.

How do you deserialize a file in Java?

To perform serialization, use the ObjectOutputStream class's writeObject method. For deserialization, use the InputObjectStream class's readObject method. The . ser extension is usually used when serializing an entity to a file in Java.

What is serializing an object in Java?

To serialize an object means to convert its state to a byte stream so that the byte stream can be reverted back into a copy of the object. A Java object is serializable if its class or any of its superclasses implements either the java. io. Serializable interface or its subinterface, java. io.

How do you delete a serialized object in Java?

You delete serialized objects by deleting whatever you stored the bytes in -- a file, a byte array, whatever. Seems like you already know the answer: you have to close the output stream. You could do that better using try-with-resources.

How can we avoid serialization of objects in Java?

To avoid Java serialization you need to implement writeObject() and readObject() method in your Class and need to throw NotSerializableException from those method.


2 Answers

Try the following:

List<Object> results = new ArrayList<Object>();
FileInputStream fis = new FileInputStream("cool_file.tmp");
ObjectInputStream ois = new ObjectInputStream(fis);

try {
    while (true) {
        results.add(ois.readObject());
    }
} catch (OptionalDataException e) {
    if (!e.eof) 
        throw e;
} finally {
    ois.close();
}

Following up on Tom's brilliant comment, the solution for multiple ObjectOutputStreams would be,

public static final String FILENAME = "cool_file.tmp";

public static void main(String[] args) throws IOException, ClassNotFoundException {
    String test = "This will work if the objects were written with a single ObjectOutputStream. " +
            "If several ObjectOutputStreams were used to write to the same file in succession, " +
            "it will not. – Tom Anderson 4 mins ago";

    FileOutputStream fos = null;
    try {
        fos = new FileOutputStream(FILENAME);
        for (String s : test.split("\\s+")) {
            ObjectOutputStream oos = new ObjectOutputStream(fos);
            oos.writeObject(s);
        }
    } finally {
        if (fos != null)
            fos.close();
    }

    List<Object> results = new ArrayList<Object>();

    FileInputStream fis = null;
    try {
        fis = new FileInputStream(FILENAME);
        while (true) {
            ObjectInputStream ois = new ObjectInputStream(fis);
            results.add(ois.readObject());
        }
    } catch (EOFException ignored) {
        // as expected
    } finally {
        if (fis != null)
            fis.close();
    }
    System.out.println("results = " + results);
}
like image 90
alf Avatar answered Sep 21 '22 04:09

alf


You can't append ObjectOutputStreams to a file. They contain headers as well as the objects you wrote. Revise your technique.

Also your EOF detection is wrong. You should catch EOFException separately. OptionalDataException means something different entirely.

like image 33
user207421 Avatar answered Sep 19 '22 04:09

user207421