-1
我有問題。現在我序列化二進制文件中的許多對象名爲student.bin反序列化java中的很多對象?
在二進制文件中添加對象數據後,現在我想要檢索寫入二進制文件中的所有數據。
但它只檢索第一個對象數據。
問題是:如何獲取文件的所有內容?
這裏是我的代碼:
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();
}
}
謝謝你的回答,但如何打印元素? –
你沒有回答完整的問題。我想分別打印所有的對象數據...例如,如果我有像這樣的對象數據(1,「John」,50),所以它應該打印,如我在我的代碼上面寫的輸出聲明。每個對象數據都必須單獨打印。 –
輸入流沒有'hasNext()'方法,並且您不能在同一個底層流上同時使用'Scanner'和'ObjectInputStream'。你還沒有嘗試過。 – EJP