![](/img/trans.png)
[英]Java, Reading two different types of variables from a file and using them as objects later
[英]Reading two different objects from file
我正在嘗試使用以下方法讀取 2 個數組列表。
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;
}
位這行不通。 它不能轉換為我保存的第二個 arraylist 類型。 那么我怎樣才能訪問它呢? 我得到的確切錯誤是:
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 個不同的數組列表呢?
使用FileOutputStream fos = new FileOutputStream("minos.dat", true);
寫第二個文件時。 true
是參數“append”的值。 否則,您將覆蓋文件內容。 這就是您閱讀同一個集合兩次的原因。
當您從文件中讀取第二個集合時,您必須跳到第二個集合的開頭。 為此,您可以記住在第一階段讀取了多少字節,然后使用方法skip()
。
但更好的解決方案是只打開一次文件(我的意思是調用新的 FileInputStream 和新的 FileOutputStream)一次,然后將其傳遞給讀取 collections 的方法。
您可以使用ObjectInputStream
從文件中讀取兩個不同的對象,但您的問題來自您重新打開 stream 的事實,因此它從您擁有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);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.