【问题标题】:Java reading/writing several objects to fileJava读取/写入多个对象到文件
【发布时间】:2014-06-14 19:17:48
【问题描述】:

我正在尝试学习如何使用蒸汽,但我似乎无法弄清楚。 我正在尝试做的事情是将几个单独的对象添加到一个文件中,然后一次检索它们。 当我尝试检索它们时,我只会得到“最后一个”插入的对象。现在我正在尝试弄清楚如何打印对象,但后来我想将它们导入到 ArrayList 中。 这是我的代码:

public class ExpenseDB {
private final static File DB = new File("C:\\Expense2s3.dat");

public static void addExpense(Expense ex) throws AddException {
        try {
            ObjectOutputStream out;
            out = new ObjectOutputStream(new FileOutputStream(DB));
            out.writeObject(ex);
            out.close();
            System.out.println("Added "+ex);
        } catch (IOException e) {
            throw new AddException();
        }
}


@SuppressWarnings("deprecation")
public static void getAllExpenses() {
    if (DB.length() == 0) return;
    try {
        ObjectInputStream in = new ObjectInputStream(new FileInputStream(DB));
        try {
            Expense exp=(Expense)in.readObject();
            System.out.println(exp);
            in.close();
         } catch (ClassNotFoundException e) {}
    } catch (IOException e) {
        System.err.println("Error");
    }
}

【问题讨论】:

  • 这里有什么问题

标签: java inputstream outputstream


【解决方案1】:

当你打开一个文件然后写入它时,它会覆盖它的内容。而是使用new FileOutputStream(DB,true) 追加到文件末尾

【讨论】:

  • 你是说 FileOutputStream 吗?
  • 是的,它起作用了:) InputStream 怎么样?我可以让它遍历对象还是必须一次导入它们?
  • @Airwavezx readObject() 一次只会返回一个对象,因此您必须循环获取所有对象。
  • 这真的行不通。每个ObjectOutputStream 将在写入对象之前输出其标题。这将导致一个包含乱码的文件,并且只能通过在循环中生成ObjectInputStream 来读取,每个对象一个。执行此操作的正确方法是保留 Collection 或使用 XML 等结构化表示。
  • 正如鲍里斯所说,我尝试了Expense exp=(Expense)in.readObject(); while (exp != null){,但没有成功。如果我坚持循环执行而不使用 Collection,我该怎么做?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-11-20
  • 2019-08-29
  • 1970-01-01
  • 1970-01-01
  • 2018-03-12
  • 1970-01-01
  • 2021-03-03
相关资源
最近更新 更多