gpt4 book ai didi

java - Java中使用ArrayList进行对象序列化和反序列化

转载 作者:太空宇宙 更新时间:2023-11-04 07:07:00 26 4
gpt4 key购买 nike

我试图序列化一个对象数组并将其写入名为 address.ser 的文件,然后从该文件读回,反序列化对象数组并显示其属性。我尝试一次序列化整个 arrayList(在读取时在单个 session 中反序列化它),并且还尝试将对象数组的每个对象一一序列化(在读取时将其一一反序列化)。问题是,在从 address.ser 文件读回时,我仅获取最后写入的对象的数据,而不获取其他对象的数据。

这是代码片段:

Employee[] a=new Employee[5];

List<Employee> arr=new ArrayList<Employee>();

for(int i=0;i<=4;i++)
{
a[i]=new Employee();
System.out.println("Enter name,age,height,weight,house_no:");
a[i].name=sc.next();
a[i].age=sc.nextInt();
a[i].height=sc.nextDouble();
a[i].weight=sc.nextDouble();
a[i].house_no=sc.nextInt();
arr.add(a[i]);
}

这是将对象写入address.ser的代码片段:

for(int i=0;i<=4;i++)
{
try
{
fout = new FileOutputStream("e:\\address.ser");
oos = new ObjectOutputStream(fout);
oos.writeObject(a[i]);
//oos.writeChars("\n");
}
catch(Exception e)
{
e.printStackTrace();
}
finally
{
oos.close();
fout.close();
}
}

这是从address.ser读取对象的代码片段:

List<Employee> recordList=new ArrayList<Employee>();
for(int i=0;i<=4;i++)
{
try
{
file = new FileInputStream("e:\\address.ser");
input = new ObjectInputStream (file);

//deserialize the List
Employee readCase=(Employee) input.readObject();
recordList.add(readCase);
System.out.print("Employee "+i+" ");
System.out.print((recordList.get(i).name)+" ");
System.out.print((recordList.get(i).age)+" ");
System.out.print((recordList.get(i).height)+" ");
System.out.print((recordList.get(i).weight)+" ");
System.out.print((recordList.get(i).house_no)+" ");
System.out.println();

}
catch(Exception e)
{
e.printStackTrace();
}
finally
{
file.close();
input.close();
}
}

最终输出为:

Output Image

最佳答案

这就是办法

public class Test {
public static void main(String[] args) {
Employee employee=new Employee("jhon");
Employee employee2=new Employee("jojo");
Employee employee3=new Employee("albin");
ArrayList<Employee> list=new ArrayList<Employee>();
list.add(employee);
list.add(employee2);
list.add(employee3);

try {
FileOutputStream outputStream=new FileOutputStream("add.ser");
ObjectOutputStream objectOutputStream= new ObjectOutputStream(outputStream);
objectOutputStream.writeObject(list);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}


try {
FileInputStream inputStream=new FileInputStream("add.ser");
ObjectInputStream objectInputStream =new ObjectInputStream(inputStream);
ArrayList<Employee> list2=(ArrayList<Employee>) objectInputStream.readObject();
for (Employee employee4 : list2) {
System.out.println(employee4.getName());
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}

关于java - Java中使用ArrayList进行对象序列化和反序列化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21213985/

26 4 0