2012-05-29 50 views
-1

我試圖將對象放在文檔中。 dat然後他們可以閱讀有誰知道哪裏錯了? 我的問題是,它能夠讀取你保存的文件,我不知道你保存它,但如果我找到文件夾中的文件... ...如何使用記錄器/播放器對象

我正在處理像這樣的物品:

public class Person { 
    public int Id; 
    public String Name; 
    public boolean Show; 

    public Persona(
      int identificator, 
      String newName, 
      boolean ShoworNot 
      ){ 
     this.Id = identificator; 
     this.Name = newName; 
     this.Show = ShoworNot; 
    } 

Thanks 
my code: 

public void WriteFile 
try { 
      FileOutputStream file = new FileOutputStream("try.dat"); 
      ObjectOutputStream exit = new ObjectOutputStream(file); 
      Iterator ite2 = people.iterator(); 
      while(ite2.hasNext()){ 
      Person person2 = (Person)ite2.next(); 
      exit.writeObject(person2); 
      exit.close(); 
     } 
      System.out.println("It's works"); 

     } 
     catch (IOException e){ 
     System.out.println("Problems with the file."); 
     } 
} 
    } 
    } 
    } 
    public void ReadFile(){ 
     try { 
FileInputStream file2 = new FileInputStream("try.dat"); 
ObjectInputStream entry = new ObjectInputStream(file2); 
entry.readObject(); 
String data = (String)entry.readObject(); 
     entry.close(); 
System.out.println(data); 
} 

catch (FileNotFoundException e) { 
System.out.println("It can't open the file document"); 
} 
catch (IOException e) { 
System.out.println("Problems with the file"); 
} 
catch (Exception e) { 
System.out.println("Error reading the file"); 
} 
} 

回答

0

如果您想使用ObjectOutputStream,則您的對象必須實現Serializable接口。只要改變public class Person {public class Person implements Serializable {

也能看到有什麼問題,在每塊catch{}e.printStackTrace()

你有一個錯誤:

entry.readObject(); 
String data = (String)entry.readObject(); 

你正在閱讀1個對象,忽略它,並試圖讀取第二個對象,但是您已經閱讀過它,因此您處於文件末尾,並且得到EndOfFileException(EOF)。刪除第一行。第二個問題是對象的類型無效。你寫一個對象Person,所以你必須閱讀Person,不String

Person data = (Person) entry.readObject(); 

另外你在文件之前您關閉流發送的所有數據後,你必須調用.flush()

exit.writeObject(person2); 
exit.flush(); 
exit.close(); 
+0

我編輯我的答案 – alaster

相關問題