如何反序列化对象?

时间:2015-02-23 16:21:54

标签: java

我正在尝试反序列化.ser文件中的某些对象存储。 问题是,即使文件包含一些对象,我也无法设法填充该数据的数组列表....

CODE:

File file=new File(path);
List<Row> deserialized=new ArrayList<Row>();
ObjectInputStream objectIn = new ObjectInputStream(new BufferedInputStream(new FileInputStream(file)));             
deserialized=(List<Row>) objectIn.readObject();

执行此操作后,反序列化始终为空。我实际上做错了什么?

编辑:我看到我得到以下异常堆栈跟踪:

java.io.EOFException
at java.io.ObjectInputStream$PeekInputStream.readFully(Unknown Source)
at java.io.ObjectInputStream$BlockDataInputStream.readShort(Unknown Source)
at java.io.ObjectInputStream.readStreamHeader(Unknown Source)
at java.io.ObjectInputStream.<init>(Unknown Source)
at com.warnings.compilation.views.TableContent.getSolvedErrors(TableContent.java:1788)
at com.warnings.compilation.views.TableContent.updateContentProvider(TableContent.java:243)
at com.warnings.compilation.views.TableContent.updateContentProviderOnRefresh(TableContent.java:1458)
at com.warnings.compilation.views.TabViewer$2.selectionChanged(TabViewer.java:305)
at org.eclipse.ui.internal.AbstractPartSelectionTracker$1.run(AbstractPartSelectionTracker.java:119)
at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42)
at org.eclipse.core.runtime.Platform.run(Platform.java:857)
at org.eclipse.ui.internal.AbstractPartSelectionTracker.fireSelection(AbstractPartSelectionTracker.java:117)

1 个答案:

答案 0 :(得分:2)

你的代码看起来很好并且应该正常工作你正确地序列化你的arraylist(例如,如果你使用readObject()读取它,那么你应该使用writeObject()来序列化它)

以下是有关序列化和反序列化ArrayList的示例。

public static void main(String[] args) throws IOException, ClassNotFoundException {
    // create a test ArrayList
    ArrayList<Integer> arr = new ArrayList<Integer>();
    for (int i = 0; i < 10; ++i)
        arr.add(i);

    // serialize ArrayList
    FileOutputStream fos = new FileOutputStream("test.ser");
    ObjectOutputStream oos = new ObjectOutputStream(fos);
    oos.writeObject(arr);
    oos.close();

    // desrialize ArrayList
    FileInputStream fis = new FileInputStream("test.ser");
    ObjectInputStream ois = new ObjectInputStream(fis);
    ArrayList<Integer> deser = (ArrayList<Integer>) ois.readObject();
    ois.close();

    System.out.println(deser.size());
    for (Integer element : deser)
        System.out.println(element);
}

如果代码中的“Row”类可序列化,则代码应该相同。