2011-07-05 45 views
0

我正在嘗試使用以下方法來讀取2個arraylist。從文件中讀取兩個不同的對象

public static ArrayList<Contestant> readContestantsFromFile() throws IOException, ClassNotFoundException { 
    FileInputStream fis = new FileInputStream("minos.dat"); 
    ObjectInputStream ois = new ObjectInputStream(fis); 

    ArrayList<Contestant> contestants = (ArrayList<Contestant>) ois.readObject(); 

    ois.close(); 

    return contestants; 
} 
public static ArrayList<Times> readContestantsFromFile() throws IOException, ClassNotFoundException { 
    FileInputStream fis = new FileInputStream("minos.dat"); 
    ObjectInputStream ois = new ObjectInputStream(fis); 

    ArrayList<times> times = (ArrayList<Times>) ois.readObject(); 
    ois.close(); 
    return times; 
} 

這是行不通的。它不能投射到我保存的第二個數組列表類型。那麼我怎樣才能訪問它?我得到確切的錯誤是這樣的:

Exception in thread "main" java.lang.ClassCastException: com.deanchester.minos.model.Contestant cannot be cast to com.deanchester.minos.model.Times 
at com.deanchester.minos.tests.testAddTime.main(testAddTime.java:31) 

,這是指該生產線是:

ArrayList<times> times = (ArrayList<Times>) ois.readObject(); 

那麼,如何從一個文件中讀出2周不同的ArrayList?

+0

爲什麼不測試它?這通常是找出問題的最佳方法。 –

+0

@Zhehao,我不想測試它,因爲想寫很多不必要的代碼,但現在就做,並且進展順利。 – Dean

回答

0

寫入第二個文件時使用FileOutputStream fos = new FileOutputStream("minos.dat", true);true是參數「append」的值。否則,您會覆蓋文件內容。這就是你兩次讀同一個集合的原因。

當您從文件中讀取第二個集合時,必須跳至第二個集合的開頭。要做到這一點,您可以記住您在第一階段讀取了多少字節,然後使用方法skip()

但更好的解決方案是隻打開一次文件(我的意思是調用新的FileInputStream和新的FileOutputStream),然後將其傳遞給讀取集合的方法。

+0

您能否介紹一些關於第二段的更多信息。什麼類是'skip()'(我可以在java API中有一個指向它的鏈接)? – Dean

0

您可以閱讀使用ObjectInputStream文件兩個不同的對象,但你的問題來自於你重新打開流,因此在文件的開頭開始,你必須在ArrayList<Contestant>,然後你ArrayList<Times>的事實。嘗試立即做所有事情並返回兩個列表:

public static ContestantsAndTimes readObjectsFromFile() throws IOException, ClassNotFoundException { 
    FileInputStream fis = new FileInputStream("minos.dat"); 
    ObjectInputStream ois = new ObjectInputStream(fis); 

    ArrayList<Contestant> contestants = (ArrayList<Contestant>) ois.readObject(); 
    ArrayList<Times> times = (ArrayList<Times>) ois.readObject(); 
    ois.close(); 

    return new ContestantsAndTimes(contestants, times); 
}