0

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);
    }
ebolton
  • 1,126
  • 3
  • 14
  • 20

2 Answers2

5

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());
}
Marko Topolnik
  • 195,646
  • 29
  • 319
  • 436
2

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.

kaliatech
  • 17,579
  • 5
  • 72
  • 84
  • Do note that, as far as character encoding issues are concerned, the solution you present has exactly the same issues as the solution employing a `PrintStream`. – Marko Topolnik Nov 06 '12 at 21:01
  • Agreed. I've since modified this answer to show how UTF-8 could be set explicitly. I've also just learned that PrintStream allows setting character encoding from constructor in recent JDKs. So there really is little difference between the two except for autoflush behavior. – kaliatech Nov 06 '12 at 21:20