我知道这个问题已经被问了一百万遍了,我已经看到了一百万个解决方案,但是没有一个对我有用。我有一个要写入文件的哈希,但是我希望哈希集中的每个元素都在单独的行中。这是我的代码:
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);
}
Run Code Online (Sandbox Code Playgroud)
错误之处在于,您尝试序列化字符串,而不仅仅是将它们打印到文件中,这与将它们打印到屏幕上的方式完全相同:
PrintStream out = new PrintStream(new FileOutputStream("HashSet.txt")));
Iterator hashSetIterator = different.iterator();
while(hashSetIterator.hasNext()){
out.println(hashSetIterator.next());
}
Run Code Online (Sandbox Code Playgroud)