我正在尝试将哈希集写入文本文件。通常,我对写入 txt 没有任何问题,因为这对我来说很简单。然而,在这种情况下我完全无能为力。
关于该类的一些背景知识:它是具有 2 个字段的 ComputerScientist 对象的哈希集;姓名和研究领域(是的,我知道我用来填充哈希集的内容不算数,我只是想测试一下是否可以使其工作)。
我知道使用文件写入器将字符串保存到哈希集的基本设置,这是我在 SO 上发现的许多类似问题所处理的,所以这些并没有真正帮助我。
我渴望学习,如果省略讽刺或侮辱性的评论,我将不胜感激。如果已经有一个类似的问题涉及将对象的哈希集写入 txt 文件,我很抱歉没有看到它。
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.");
}
}
}
更新: 如果我包含以下代码会有帮助吗?我仍在计算 .write() 行括号中的内容。我的脑子炸了:/
for (int i = 0; i < computerScientistSet.size(); i++) {
computerScientistWriter.write();
}
最佳答案
由于我假设您希望将集合写入文件以便稍后读取,因此最好的方法是不要重新发明轮子并使用序列化。
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();
}
}
关于java - 使用 filewriter 将哈希集写入 txt,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29198648/