【发布时间】:2013-12-15 04:10:27
【问题描述】:
我正在编写一个 java 程序作为对自己学习的挑战,我目前在序列化和反序列化 arraylist 时遇到了麻烦。当我反序列化时,所有的值都是空的。
这是最初序列化列表的函数:
private void saveModList(ArrayList<Moderator> m) {
try {
ObjectOutputStream fOut = new ObjectOutputStream(new FileOutputStream("data/modlist.ctm"));
fOut.writeObject(m);
fOut.close();
} catch(IOException ex) {
JOptionPane.showMessageDialog(null, "Could not save moderator list.",
"Save error", JOptionPane.ERROR_MESSAGE);
ex.printStackTrace();
}
}
这是反序列化列表的函数:
public static ArrayList<Moderator> openModList() {
try {
ObjectInputStream fIn = new ObjectInputStream(new FileInputStream("data/modlist.ctm"));
try {
return (ArrayList<Moderator>) fIn.readObject();
} catch (ClassNotFoundException ex) {
JOptionPane.showMessageDialog(null, "Could not open moderator list",
"Read error", JOptionPane.ERROR_MESSAGE);
ex.printStackTrace();
}
fIn.close();
} catch(FileNotFoundException ex) {
JOptionPane.showMessageDialog(null, "Could not load moderator data. File not found.",
"Moderator file not found.", JOptionPane.ERROR_MESSAGE);
ex.printStackTrace();
} catch(EOFException ex) {
} catch(IOException ex) {
JOptionPane.showMessageDialog(null, "Could not load moderator data.",
"Error", JOptionPane.ERROR_MESSAGE);
ex.printStackTrace();
}
//If something screws up, return null, and the user will not be logged in
return null;
}
这会调用函数进行反序列化
ArrayList<Moderator> modLoginList = new ArrayList<Moderator>();
modLoginList = Main.openModList();
//Check all of the moderators.
//If one of them matches up to a moderator username and password, log them in
for(int i = 0; i < modLoginList.size(); i++) {
if(modLoginList.get(i).name.equals(username) && modLoginList.get(i).password.equals(password)) {
loggedIn = true;
break;
}
}
执行此操作时,我还会在 if 语句中收到 NullPointerException,检查主持人的凭据是否有效。当我去尝试直接打印出这些值时,它们是空的。主持人类确实实现了可序列化并具有序列版本 ID。任何关于为什么会发生这种情况以及如何解决它/更好的方法来做到这一点的建议都非常感谢。
此外,它不只是因为没有可读取的内容或出现问题而直接返回 null。
【问题讨论】:
-
您在哪里/如何称呼
saveModList(...)以及您传递给它的确切是什么?我强烈怀疑它实际上是在保存一个空值列表。 -
你为什么要创建
new ArrayList然后立即替换它? -
你能贴出调用
saveModList()的代码吗?
标签: java serialization arraylist