简体   繁体   中英

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). I think you you want to use a PrintWriter instead. 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). 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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