问题描述
我已经将一个arraylist序列化为一个文件,但是很难将它们反序列化回一个arraylist并打印出来。如何编辑我的代码?谢谢!
I have serialized an arraylist to a file, but have difficulties deserializing them back into an arraylist and print them. How can I edit my code? Thanks!
这是序列化方法:
public static void writeMembersToDisk(ArrayList<Member> membersList) {
ObjectOutputStream out = null;
try {
out = new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream("members.s")));
for(Member cmd : membersList) {
out.writeObject(cmd);
}
} catch (Exception e) {
System.err.println("Error: " + e.toString());
} finally {
try {
out.close();
} catch (IOException e) {
System.err.println("Error: " + e.toString());
}
}
}
我不知道如何将文件反序列化回arraylist,这是我的代码:
I don't know how to deserialize the file back to the an arraylist, this is my code:
public static ArrayList<Member> readMembersFromDisk() {
ArrayList<Member> cmd = null;
try {
FileInputStream is = new FileInputStream("members.s");
ObjectInputStream os = new ObjectInputStream(is);
cmd = (ArrayList) os.readObject();
os.close();
} catch (Exception e) {
System.err.println("Error: " + e.toString());
}
return cmd;
}
当我尝试打印数组列表时,出现错误: java.lang.ClassCastException:成员不能转换为java.util.ArrayList
When I try to print the arraylist, I get an error: "java.lang.ClassCastException: Member cannot be cast to java.util.ArrayList"
public static void main(String[] args) {
ArrayList<Member> list = MembersListFileManager.readMembersFromDisk();
System.out.println(list);
}
推荐答案
您正在写一个<$
You are writing one Member
object at a time from the original list.
for(Member cmd : membersList) {
out.writeObject(cmd);
}
但是在阅读时,您试图投射成员
对象放入 ArrayList
中是错误的。
But while reading you're trying to cast a Member
object into an ArrayList
which is wrong.
您需要强制读取通过执行以下操作来反对成员
:
You need to cast the read object to Member
by doing something like this:
Member member = (Member) os.readObject();
但这只会获取序列化的第一个对象。要获取所有对象,请遍历并继续将每个成员对象添加到arraylist中。
But this will just fetch the first object serialized. To get all the objects, loop through and keep adding each member object read into the arraylist.
// Pseudo-code
loop till objects are there{
Member member = (Member) os.readObject(); // read the object
cmd.add(member); // add it to the list
}
其中一种循环方法是,
while (true) {
try {
Member member = (Member) os.readObject();
// Do something with the object
} catch (EOFException e) {
break; // Break when the end-of-file is reached
}
}
os.close();
这篇关于反序列化文件并返回包含文件中对象的arraylist的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!