【问题标题】:Read many ArrayList Objects out of File with ObjectInputStream?使用 ObjectInputStream 从文件中读取许多 ArrayList 对象?
【发布时间】:2012-07-31 13:19:26
【问题描述】:

我将 ArrayLists 写入文件。我用 FileInputStream 阅读它。但总是只有“第一个”ArrayList 是通过阅读出现的。我用 readInt() / wirteInt() 和循环尝试了它,但是通过调用 readInt() --> EOF 总是抛出异常 我想将此文件中的所有 ArrayList 读入 ArrayList。我的应用程序需要持久化,所以我序列化了 ArrayLists。

写入文件:

        try {         
        FileOutputStream fos = new FileOutputStream(_cache, true);
        ObjectOutputStream os = new ObjectOutputStream(fos);
        // os.writeInt(newValueList.size()); // Save size first
        os.writeObject(newValueList); 

        os.flush();
        os.close();

    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

从文件中读取:

 List cachedValueList = new ArrayList<String>();
    ObjectInputStream o = new ObjectInputStream(new FileInputStream("caching.io"));
  //  int count = o.readInt(); // Get the number of regions

    try {

            cachedValueList.add(o.readObject());

    } catch (EOFException e) {
        o.close();
        e.printStackTrace();
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (ClassNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

【问题讨论】:

  • 你的循环在哪里?你为什么不简单地写一个 List 而不是循环并一个一个地写所有的列表?
  • os.writeObject(newValueList); - newValueList 的类型是什么? cachedValueList.add(o.readObject()); - 你打算读什么?看来您打算阅读String。我认为您尝试编写某种列表,然后读取列表对象并将其添加到另一个列表(隐式转换为字符串)
  • @JBNizet 我怀疑问题是他重复使用同一个列表。
  • while ((obj = o.readObject()) != null) { if (obj instanceof ArrayList) { cachedValueList = (List) obj; _historyValueList.add(cachedValueList); } }
  • @MaxL 请注意,该循环不正确。 readObject() 不会在流结束时返回 null:它会抛出 EOFException。 “无效类型代码:AC”表示您在同一个套接字上使用了多个 ObjectOutputStream:不要那样做。

标签: java serialization java-io


【解决方案1】:

如果你多次写同一个列表,它只会写一次。之后它将使用相同的引用但内容将相同(任何对象都是如此)

如果您在 writeObject() 之间调用 reset(),它将每次发送一个新的列表副本。

【讨论】:

    猜你喜欢
    • 2013-07-07
    • 2014-05-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-20
    • 1970-01-01
    相关资源
    最近更新 更多