Write hashset to txt using filewriter

2019-08-12 06:10发布

I am trying to write a hashset to a text file. Normally, I have no issues with writing to txt as it is simple for me. However, in this case I am absolutely clueless.

A bit of background about the class: it is a hashset of ComputerScientist objects with 2 fields; name, and field of research (and yes, I know what I put to fill up the hashset does not count, I was only trying to test to see if I could get this to work).

I know the basic setup to use filewriter to save strings to hashset which is what a lot of the similar questions which I found on SO dealt with, so those did not really help me.

I am eager to learn, and would appreciate it if snide or insulting comments were left out. And if there is already a similar question which deals with writing hashsets of objects to txt file, I apologize for not seeing it.

import java.util.HashSet;
import java.io.FileWriter;
import java.io.IOException;
/**
* Write a description of class ComputerScientistSet here.
* 
* @author (your name) 
* @version (a version number or a date)
*/
public class ComputerScientistSet
{
private HashSet<ComputerScientist> computerScientistSet;
private FileWriter computerScientistWriter;
private String fileName;
/**
 * Constructor for objects of class ComputerScientistSet
 */
public ComputerScientistSet(){
    computerScientistSet = new HashSet<ComputerScientist>();
    fileName = "scientist-names.txt";
    setComputerScientistSet();
}

private void setComputerScientistSet(){
    computerScientistSet.add (new ComputerScientist("Bob", "Robotics"));
    computerScientistSet.add (new ComputerScientist("Tim", "VR"));
    computerScientistSet.add (new ComputerScientist("Jake", "Nuclear Fision"));
    computerScientistSet.add (new ComputerScientist("Joe", "Snapple"));
    computerScientistSet.add (new ComputerScientist("Jane", "Magnets"));
    computerScientistSet.add (new ComputerScientist("Mary", "PC"));
}

public void writeNames(){
    try{
        computerScientistWriter = new FileWriter(fileName, true);
        computerScientistWriter.write(computerScientistSet);
        computerScientistWriter.close();
    }
    catch(IOException ioException){
        System.out.println("Error.");
    }
}
}

Update: Would it help if I include the following code? I am still working out what would go in the parentheses by the .write() line. My brain is fried :/

for (int i = 0; i < computerScientistSet.size(); i++) {
            computerScientistWriter.write();
        }

3条回答
地球回转人心会变
2楼-- · 2019-08-12 06:40

Since I assume you want to write the set to a file to read it in later, the best way would be not to reinvent the wheel and to use serialization instead.

public class Person implements java.io.Serializable {
    private String name;
    // constructor, setter, getter, etc
}

public static void main(String[] args) {
    Set<Person> persons = new HashSet<Person>();
    persons.add(new Person("foo");
    try {
        FileOutputStream fileOut = new FileOutputStream("/tmp/persons.data");
        ObjectOutputStream out = new ObjectOutputStream(fileOut);
        out.writeObject(e);
        out.close();
        fileOut.close();
     } catch(IOException e) {
         e.printStackTrace();
     }
     try {
         FileInputStream fileIn = new  FileInputStream("/tmp/persons.data");
         ObjectInputStream in = new ObjectInputStream(fileIn);
         Set<Person> persons = (Set<Person>) in.readObject();
         in.close();
         fileIn.close();
     } catch(Exception e) {
         e.printStackTrace();
     }
}
查看更多
啃猪蹄的小仙女
3楼-- · 2019-08-12 06:40

Based on your comments here your output currently shows many entries as: ComputerScientist@7e384e79

Rather than rely on that link, I strongly encourage you to update this question with an example of what your code here would currently output.

When you see output like ComputerScientist@7e384e79 it means the ComputerScientist class isn't overriding the toString() method to show it's state. You can do that to make your technique work. You can do it by hand or use a IDE that offers a refactoring to make it less tedious but you don't get it for free. You'll need it implemented for every class you wish to output this way.

enter image description here

enter image description here

查看更多
做自己的国王
4楼-- · 2019-08-12 06:49

Ended up using this coding:

public void writeNames(){
 try{
        computerScientistWriter = new FileWriter(fileName, true);                       
        for(ComputerScientist list: computerScientistSet){
               computerScientistWriter.write(list.getName() + " , " + "\n" + list.getField() + System.lineSeparator() );
        }
        computerScientistWriter.close();
    }
    catch(IOException ioException){
        System.out.println("Error.");
    }
}
查看更多
登录 后发表回答