How to empty a HashSet in a Java file


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?

Have a look at serialization.

Here's an example:

String filename = "savedHashSet.dat";

// Create it
Set<String> someStrings = new HashSet<String>();

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


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

Related links:

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.