Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to save list items on disk instead of memory in Java

Tags:

java

I'm looking for a data structure same as ArrayList in Java that saves items on disk instead of memory. Does java have such a data structure? Thanks

I want to have a dynamic structure that saves items on memory and when its size exceeds some value, save new items on disk until the size goes below the value.

like image 636
user468889 Avatar asked Oct 13 '10 08:10

user468889


3 Answers

You can yourself do it: Serialize the ArrayList to disk.

Make sure that the contents of the list are serializable, i.e., the objects in the list should implement the Serializable interface.

then
to write to file:

ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(fileName));
oos.writeObject(list);
oos.flush();
oos.close();

To read from file:

ObjectInputStream ois = new ObjectInputStream(new FileInputStream(fileName));
List<YourClass> list = ois.readObject();
ois.close()
like image 108
Nivas Avatar answered Nov 07 '22 09:11

Nivas


If you need to change data in this ArrayList often, changing disk image, then why not consider something like http://www.hibernate.org/ ? Well, it is much more complicated than ArrayList but also gives more featues.

like image 2
maxim_ge Avatar answered Nov 07 '22 09:11

maxim_ge


Just to make the set of answers complete :)

XStream

XStream is a simple library to serialize objects to XML and back again.

Person joe = new Person("Joe", "Walnes");
joe.setPhone(new PhoneNumber(123, "1234-456"));
joe.setFax(new PhoneNumber(123, "9999-999"));

Now, to convert it to XML, all you have to do is make a simple call to XStream:

String xml = xstream.toXML(joe);

The resulting XML looks like this:

<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>
like image 2
willcodejavaforfood Avatar answered Nov 07 '22 10:11

willcodejavaforfood