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