简体   繁体   English

用Java将哈希集保存到文件

[英]Saving a Hashset to a file in Java

I know this question has been asked a million times and I have seen a million solutions but none that work for me. 我知道这个问题已经被问了一百万遍了,我已经看到了一百万个解决方案,但是没有一个对我有用。 I have a hashet that I want to write to a file but I want each element in the Hashset in a separate line. 我有一个要写入文件的哈希,但是我希望哈希集中的每个元素都在单独的行中。 Here is my code: 这是我的代码:

    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);
    }

Where you got it wrong is that you are trying to serialize the strings instead of just printing them to the file, exactly the same way you print them to the screen: 错误之处在于,您尝试序列化字符串,而不仅仅是将它们打印到文件中,这与将它们打印到屏幕上的方式完全相同:

PrintStream out = new PrintStream(new FileOutputStream("HashSet.txt")));
Iterator hashSetIterator = different.iterator();
while(hashSetIterator.hasNext()){
    out.println(hashSetIterator.next());
}

ObjectOutputStream will try to serialize the String as an object (binary format). ObjectOutputStream将尝试将String序列化为一个对象(二进制格式)。 I think you you want to use a PrintWriter instead. 我认为您想改用PrintWriter。 Example: 例:

PrintWriter writer= new PrintWriter( new OutputStreamWriter( new FileOutputStream( "HashSet.txt"), "UTF-8" )); 
while(hashSetIterator.hasNext()) {
    String o = hashSetIterator.next();
    writer.println(o);
}

Note that per this answer and the answer from Marko, you can use PrintStream or PrintWriter to output strings (characters). 请注意,根据此答案以及Marko的答案,您可以使用PrintStream或PrintWriter输出字符串(字符)。 There is little difference between the two, but be sure to specify a character encoding if you work with non standard characters or need to read/write files across different platforms. 两者之间几乎没有什么区别,但是如果您使用非标准字符或需要跨不同平台读取/写入文件,请确保指定字符编码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM