我使用serialastion将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 :(得分: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
。再次,堆栈跟踪将非常有用。