2011-07-05 37 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); 
}