2015-11-25 39 views
-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(); 

} 
} 

回答

0

使用while循環。流有一個hasNext方法,只要文件中有未讀字節,就可以繼續讀對象。請注意,如果文件末尾有額外的字節,則會導致錯誤。

List<Binary> binaries = new ArrayList<Binary>(); 
while(in.hasNext()) { 
    binaries.add((Binary) in.readObject()); 
} 

我很抱歉,如果這是無效的,我現在無法進行測試。

編輯:有可能hasNext是掃描儀而不是流的方法,在這種情況下,您必須將流包裝到掃描儀對象中:Scanner read = new Scanner(in)

+0

謝謝你的回答,但如何打印元素? –

+0

你沒有回答完整的問題。我想分別打印所有的對象數據...例如,如果我有像這樣的對象數據(1,「John」,50),所以它應該打印,如我在我的代碼上面寫的輸出聲明。每個對象數據都必須單獨打印。 –

+0

輸入流沒有'hasNext()'方法,並且您不能在同一個底層流上同時使用'Scanner'和'ObjectInputStream'。你還沒有嘗試過。 – EJP