【发布时间】:2015-11-25 23:58:43
【问题描述】:
我有一个问题。现在我在一个名为 student.bin 的二进制文件中序列化许多对象
在二进制文件中添加对象数据后,现在我想检索写入二进制文件中的所有数据。
但它只检索第一个对象数据。
问题是:如何获取文件的所有内容?
这是我的代码:
import java.util.Scanner;
import java.io.*;
import java.io.Serializable;
public class Binary implements Serializable{
public int id;
public String name;
public int grade;
public static void main(String argv[]) throws IOException, ClassNotFoundException
{
Binary b = new Binary();
Scanner sc = new Scanner(System.in);
System.out.printf("Enter student id: ");
b.id = sc.nextInt();
System.out.printf("Enter student name: ");
b.name = sc.next();
System.out.printf("Enter student grade: ");
b.grade = sc.nextInt();
ObjectOutputStream bin = new ObjectOutputStream(new FileOutputStream("C:\\Users\\فاطمة\\Downloads\\student.bin",true));
bin.writeObject(b);
bin.close();
ObjectInputStream in = new ObjectInputStream(new FileInputStream("C:\\Users\\فاطمة\\Downloads\\student.bin"));
Binary b2 = (Binary)in.readObject();
System.out.println("Student ID: " + b2.id);
System.out.println("Student Name: " + b2.name);
System.out.println("Student Grade: " + b2.grade);
in.close();
}
}
【问题讨论】:
标签: java serialization file-io deserialization