0
我正在制作一个java程序作为对自己学习的挑战,而我目前在序列化和反序列化ArrayList时遇到了麻烦。当我反序列化所有的值为空。反序列化数组列表时,Java所有值都为null
这是最初连载列表功能:
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,检查是否th主持人的凭证是有效的。当我去尝试打印出值时,它们是空的。主持人类确实实现了可序列化并具有序列版本ID。任何建议,为什么发生这种情况,以及如何解决它/更好的方式来做到这一点非常感谢。
此外,它不仅仅是完全返回null,因为没有什么可读的,或出了什么问题。
你在哪里/如何调用'saveModList(...)'以及你传递给它的内容?我强烈怀疑它实际上是保存了一个空值列表。 –
为什么要创建'new ArrayList',然后立即替换它? – chrylis
你可以发布调用'saveModList()'的代码吗? – initramfs