【发布时间】: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