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>();
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:
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.
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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With