Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to dump a HashSet into a file in Java

One of my program reads a file and does some processing and builds an in-memory hash set. I would like to store this built hash set as such in a file, so that another program can read it off later on as such and take the whole image in its in-memory data structure hash set. How to achieve this?

like image 240
xyz Avatar asked Oct 06 '11 11:10

xyz


2 Answers

Have a look at serialization.

Here's an example:

String filename = "savedHashSet.dat";

// Create it
Set<String> someStrings = new HashSet<String>();
someStrings.add("hello");
someStrings.add("world");

// Serialize / save it
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(filename));
oos.writeObject(someStrings);

...
...
...

// Deserialize / load it
ObjectInputStream ois = new ObjectInputStream(new FileInputStream(filename));
Set<String> aNewSet = (HashSet<String>) ois.readObject();

Related links:

  • Java Serialization Tutorial
  • The Java™ Tutorials: Serializable Objects (from Oracle)

Note that the objects you store in the HashSet needs to be serializable too. Personally, I usually rely on "manual" serialization. If for instance your HashSet contains primitive types, Strings, or lists of Strings or something else which is easy enough to "manually" write to disk, I'd probably consider doing that.

like image 199
aioobe Avatar answered Oct 26 '22 23:10

aioobe


Hash set is Serializable. That means you actually can write the Object into a file and read it again. Read this: http://java.sun.com/developer/technicalArticles/Programming/serialization/

like image 37
Simiil Avatar answered Oct 27 '22 00:10

Simiil