我知道这个问题已经被问了一百万次,我已经看到了一百万个解决方案,但没有一个对我有用。我有一个散列,我想将其写入文件,但我希望散列集中的每个元素都在单独的行中。 这是我的代码:
Collection<String> similar4 = new HashSet<String>(file268List);
Collection <String> different4 = new HashSet<String>();
different4.addAll(file268List);
different4.addAll(sqlFileList);
similar4.retainAll(sqlFileList);
different4.removeAll(similar4);
Iterator hashSetIterator = different.iterator();
while(hashSetIterator.hasNext()){
System.out.println(hashSetIterator.next());
}
ObjectOutputStream writer = new ObjectOutputStream(new FileOutputStream("HashSet.txt"));
while(hashSetIterator.hasNext()){
Object o = hashSetIterator.next();
writer.writeObject(o);
}
最佳答案
错误之处在于您试图序列化字符串,而不是仅仅将它们打印到文件中,这与将它们打印到屏幕上的方式完全相同:
PrintStream out = new PrintStream(new FileOutputStream("HashSet.txt")));
Iterator hashSetIterator = different.iterator();
while(hashSetIterator.hasNext()){
out.println(hashSetIterator.next());
}
关于java - 在 Java 中将哈希集保存到文件中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13258441/