【问题标题】:how to deserialize an ArrayList of data from a binary file in Java?如何从Java中的二进制文件反序列化数据的ArrayList?
【发布时间】:2011-10-30 04:19:18
【问题描述】:

我已经使用序列化将 arrayList 保存到二进制文件中。我现在如何从二进制文件中检索这些数据?

这是我用来序列化的代码

public void createSerialisable() throws IOException
{
    FileOutputStream fileOut =  new FileOutputStream("theBkup.ser");
    ObjectOutputStream out =  new ObjectOutputStream(fileOut);
    out.writeObject(allDeps);
    options();
}

这是我试图用来反序列化 arrayList 的代码:

public void readInSerialisable() throws IOException
{
    FileInputStream fileIn = new FileInputStream("theBKup.ser");

    ObjectInputStream in = new ObjectInputStream(fileIn);

    try
    {
     ArrayList readob  = (ArrayList)oi.readObject();  
               allDeps = (ArrayList) in.readObject();
    }
    catch (IOException exc)
    {
        System.out.println("didnt work");
    }
}

allDeps 是类构造器中声明的数组列表。我试图将文件中的 arrayList 保存到此类中声明的 arrayList 中。

【问题讨论】:

  • 具有名称和位置的部门
  • 是的,带有 oi 的那一行实际上不应该是他们的。我只是用那条线来知道如何写它下面的线。只需取消那条线。很抱歉造成混乱
  • 在这里查看我的答案:stackoverflow.com/questions/6683582/…

标签: java serialization arraylist


【解决方案1】:

您的代码大部分是正确的,但有一个错误和几件事可能会使其更好地工作。我用星号突出显示了它们(显然,我不能在“代码”模式下将它们加粗)。

public void createSerialisable() throws IOException
{
    FileOutputStream fileOut =  new FileOutputStream("theBkup.ser");
    ObjectOutputStream out =  new ObjectOutputStream(fileOut);
    out.writeObject(allDeps);
    **out.flush();** // Probably not strictly necessary, but a good idea nonetheless
    **out.close();** // Probably not strictly necessary, but a good idea nonetheless
    options();
}

public void readInSerialisable() throws IOException
{
    FileInputStream fileIn = new FileInputStream("theBKup.ser");

    ObjectInputStream in = new ObjectInputStream(fileIn);

    try
    { 
        **// You only wrote one object, so only try to read one object back.**
        allDeps = (ArrayList) in.readObject();
    }
    catch (IOException exc)
    {
        System.out.println("didnt work");
        **exc.printStackTrace();** // Very useful for findout out exactly what went wrong.
    }
}

希望对您有所帮助。如果您仍然发现问题,请确保发布堆栈跟踪和一个完整的、独立的、可编译的示例来演示该问题。

请注意,我假设allDeps 包含实际上是Serializable 的对象,并且您的问题出在readInSerialisable 而不是createSerialisable。同样,堆栈跟踪将非常有用。

【讨论】:

  • 非常感谢卡梅隆,但是..它仍然无法编译,“它说必须捕获或声明未报告的异常 ClassNotFound 被抛出”在线:allDeps1 = (ArrayList)in.readObject() ;
  • 哦。您没有提到这是一个 compile 错误。这很简单:在try 块之后添加一个catch (ClassNotFoundException e) 块。或者只是将catch (IOException exc) 更改为catch (Exception exc)
猜你喜欢
  • 1970-01-01
  • 2023-03-10
  • 2016-09-15
  • 2020-03-07
  • 1970-01-01
  • 2021-12-21
  • 2016-09-29
  • 2011-01-14
  • 2014-01-04
相关资源
最近更新 更多