【问题标题】:Reading two different objects from file从文件中读取两个不同的对象
【发布时间】:2011-07-05 19:57:01
【问题描述】:

我正在尝试使用以下方法读取 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;
}

这不起作用。它不能转换为我保存的第二个数组列表类型。那么我怎样才能访问它呢?我得到的确切错误是:

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 个不同的数组列表呢?

【问题讨论】:

  • 你为什么不测试一下?这通常是找出答案的最佳方式。
  • @Zhehao,我不想测试它,因为我想写很多不必要的代码,但现在做起来,进展顺利。

标签: java java-io


【解决方案1】:

写入第二个文件时使用FileOutputStream fos = new FileOutputStream("minos.dat", true);true 是参数“append”的值。否则,您将覆盖文件内容。这就是您阅读同一个集合两次的原因。

当您从文件中读取第二个集合时,您必须跳到第二个集合的开头。为此,您可以记住您在第一阶段读取了多少字节,然后使用方法skip()

但更好的解决方案是只打开一次文件(我的意思是调用 new FileInputStream 和 new FileOutputStream)一次,然后将其传递给读取集合的方法。

【讨论】:

  • 您能否提供更多关于您的第二段的信息。 skip() 属于什么类(我可以在 java API 中提供指向它的链接)吗?
【解决方案2】:

您可以使用ObjectInputStream 从一个文件中读取两个不同的对象,但您的问题来自这样一个事实:您重新打开流,因此它从您拥有ArrayList&lt;Contestant&gt; 的文件的开头开始,然后您@ 987654324@。尝试一次做所有事情并返回两个列表:

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);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-12-31
    • 1970-01-01
    • 2016-08-15
    • 2013-04-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多