我尝试编写一个 key 持有者,并且想使用 ObjectOutputStream 将密码写入 .dat 文件,然后使用 ObjectInputStream 读取它们。这是我编写对象的代码:
public void toFile()
{
try
{
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("passwords.dat"));
for(int i = 0; i<this.nrOfPW; i++)
{
if(this.PWlist[i] instanceof longPW)
{
oos.writeObject((longPW)this.PWlist[i]);
}
else
{
oos.writeObject((PinPW)this.PWlist[i]);
}
}
oos.close();
}
catch(IOException e)
{
e.getStackTrace();
}
}
这似乎有效,但是当我尝试再次读取文件并将对象放入 PWlist 数组中时,它说 PinPW 不可序列化,即使 PinPW 实现了 Serialized 并且已导入。 PinPW (Info) 的基类也实现了 Serialized 并导入它。这是我读取文件的代码:
public void fromFile()
{
try
{
ObjectInputStream objIn = new ObjectInputStream(new FileInputStream("passwords.dat"));
while(objIn.readObject() != null)
{
if(this.nrOfPW == this.PWlist.length)
{
expand(10);
}
if(objIn.readObject() instanceof PinPW)
{
this.PWlist[this.nrOfPW] = (PinPW)objIn.readObject();
this.nrOfPW++;
}
else
{
this.PWlist[this.nrOfPW] = (longPW)objIn.readObject();
this.nrOfPW++;
}
}
objIn.close();
}
catch(EOFException e)
{
e.getStackTrace();
}
catch(IOException ex)
{
ex.printStackTrace();
}
catch(ClassNotFoundException ex)
{
ex.printStackTrace();
}
}
PWlist数组是一个Info数组,PinPW和longPW扩展了Info。
我该如何解决这个问题?
最佳答案
让我们修复“第一个错误,首先”...
在此代码中:
while(objIn.readObject() != null) // reads object, tests then *discards* it
{
...
if(objIn.readObject() instanceof PinPW) // reads object, tests then *discards* it
{
this.PWlist[this.nrOfPW] = (PinPW)objIn.readObject(); // conditionally read an object
this.nrOfPW++;
}
else
{
this.PWlist[this.nrOfPW] = (longPW)objIn.readObject(); // conditionally read an object
this.nrOfPW++;
}
}
每次循环迭代时,您实际上都会读取 3 个对象。第一次读取对象以检查流中是否有一个对象时,下次读取对象并确定其类型时,然后将其丢弃。 然后您读取第三个对象并根据丢弃对象的类型对其进行强制转换。
此外,如EJP正确指出,确定 ObjectInputStream 的流结束的正确方法是捕获文件结束异常。
您想这样做:
try
{
while (true)
{
final Object o = objIn.readObject(); // read the object from the stream
...
if (o instanceof PinPW)
{
this.PWlist[this.nrOfPW] = (PinPW) o; // cast to correct type
this.nrOfPW++;
}
else
{
this.PWlist[this.nrOfPW] = (longPW) o; // cast to correct type
this.nrOfPW++;
}
}
}
catch (EOFException e)
{
// end of stream reached ...
// ... close the file descriptor etc ...
}
关于java - 无法从 .dat 文件读取可序列化类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10939951/