如何使用Java将HashSet转储到文件中

xyz*_*xyz 4 java serialization

我的一个程序读取文件并进行一些处理并构建内存中的哈希集.我想将这个构建的哈希集存储在一个文件中,以便其他程序可以在以后读取它并将整个图像放在其内存中的数据结构哈希集中.怎么做到这一点?

aio*_*obe 14

看看序列化.

这是一个例子:

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();
Run Code Online (Sandbox Code Playgroud)

相关链接:


请注意,存储在HashSet中的对象也需要可序列化.就个人而言,我通常依靠"手动"序列化.例如,如果您的HashSet包含原始类型,字符串或字符串列表或其他易于"手动"写入磁盘的内容,我可能会考虑这样做.