2011-10-30 39 views
0

我已经使用serialastion将arrayList保存到二进制文件中。我现在如何从二进制文件中检索这些数据?如何从Java中的二进制文件反序列化数据的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。

+0

什么是数组列表? –

+0

有部门名称和地址 – Binyomin

+0

什么是'oi'? –

回答

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。同样,堆栈跟踪将非常有帮助。

+0

非常感谢卡梅隆,但.. 它仍然不能编译,“其称未报告的异常ClassNotFound的必须捕获或声明抛出” 在线:allDeps1 =(ArrayList的)in.readObject(); – Binyomin

+0

哦。你没有提到它是一个* compile *错误。这很简单:在try块后添加一个catch(ClassNotFoundException e)块。或者只是将catch(IOException exc)更改为catch(Exception exc)'。 –

+0

感谢您的帮助,现在一切正常:) – Binyomin

相关问题