Write hashset to txt using filewriter

[亡魂溺海] 提交于 2020-01-05 20:29:09

问题


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

回答1:


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



回答2:


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



回答3:


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.



来源:https://stackoverflow.com/questions/29198648/write-hashset-to-txt-using-filewriter

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!