嗨 我创建了一个名为“Human”的类,该类的每个对象都有一个名称和类型,可以是学生或教师。我创建了另一个类 main,它创建 Human 对象,并将类型和名称分配给对象,并将该对象添加到 linkedList 中。现在我想把这个linkedList写入一个文件,但我不知道怎么做。我必须将对象及其类型写入该 linkedList 中。我创建了以下作为主类,但在写入文件部分时遇到问题。你能指导一下吗?
public class Testing {
public static LinkedList<Human> link =new LinkedList<Human>();
static FileOutputStream fop;
public static void main(String args[])
{
File f=new File("textfile1.txt");
try {
fop=new FileOutputStream(f);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Human hm = new Human();
Human hum = new Human();
hm.setName("Anna");
hm.setType("Student");
hum.setName("Elvis");
hum.setType("Instructor");
link.add(hm);
link.add(hum);
for (Human h : link) {
fop.write(h.getType());
fop.write(h);
}
}
}
最佳答案
PrintStream p = new PrintStream(fop);
for (Human h : link) {
p.println(h.getType());
p.println(h);
}
p.close();
假设您已经实现了 toString人类的方法。
关于java - java 写入文件的帮助,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4186176/