【发布时间】:2011-04-24 17:22:51
【问题描述】:
我正在寻找一种与 Java 中的 ArrayList 相同的数据结构,它将项目保存在磁盘而不是内存上。 java有这样的数据结构吗? 谢谢
我想要一个动态结构,将项目保存在内存中,当其大小超过某个值时,将新项目保存在磁盘上,直到大小低于该值。
【问题讨论】:
标签: java
我正在寻找一种与 Java 中的 ArrayList 相同的数据结构,它将项目保存在磁盘而不是内存上。 java有这样的数据结构吗? 谢谢
我想要一个动态结构,将项目保存在内存中,当其大小超过某个值时,将新项目保存在磁盘上,直到大小低于该值。
【问题讨论】:
标签: java
您可以自己做:将ArrayList 序列化到磁盘。
确保列表的内容是可序列化的,即列表中的对象应该实现Serializable接口。
然后
写入文件:
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(fileName));
oos.writeObject(list);
oos.flush();
oos.close();
从文件中读取:
ObjectInputStream ois = new ObjectInputStream(new FileInputStream(fileName));
List<YourClass> list = ois.readObject();
ois.close()
【讨论】:
如果您需要经常更改此 ArrayList 中的数据,更改磁盘映像,那么为什么不考虑 http://www.hibernate.org/ 之类的东西呢?嗯,它比 ArrayList 复杂得多,但也提供了更多的功能。
【讨论】:
只是为了让这组答案完整:)
XStream 是一个简单的库 将对象序列化为 XML 并返回 再次。
Person joe = new Person("Joe", "Walnes");
joe.setPhone(new PhoneNumber(123, "1234-456"));
joe.setFax(new PhoneNumber(123, "9999-999"));
现在,要将其转换为 XML,您只需简单调用 XStream:
String xml = xstream.toXML(joe);
生成的 XML 如下所示:
<person>
<firstname>Joe</firstname>
<lastname>Walnes</lastname>
<phone>
<code>123</code>
<number>1234-456</number>
</phone>
<fax>
<code>123</code>
<number>9999-999</number>
</fax>
</person>
【讨论】:
查看http://jakarta.apache.org/jcs/。这提供了一种管理磁盘和内存上的对象的方法。另一种可能的解决方案可能是使用http://code.google.com/p/pcollections/
【讨论】:
MapDB (mapdb.org) 是一个库,可将 Java 对象以各种集合的形式保存到磁盘:Sets、Maps、Queues。
它支持缓存,因此您可以将最常用的项目保存在内存中。
【讨论】:
另一种节省语言和传输中立优势的方法是使用 Google 的Protocol Buffers。
【讨论】:
见https://dzone.com/articles/a-filebasedcollection-in-java-for-big-collections
try(FileBasedCollection<Integer> fbc = new FileBasedCollection<>()) {
for(int i = 1; i < 1000_000; i++) {
fbc.add(i);
}
long sum = 0;
try(FileBasedIterator<Integer> iter = fbc.iterator()) {
while(iter.hasNext()) {
Integer i = iter.next();
sum += i;
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("sum: " + sum);
}
【讨论】: