繁体   English   中英

从文件中读取两个不同的对象

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM