2010-11-15 39 views
2

嗨 我创建了一个名为'Human'的类,该类的每个对象都有一个名称和一个可以是学生或教师的类型。我创建了另一个创建Human对象的类主类,并为对象分配类型和名称,并将该对象添加到linkedList中。现在我想将这个链接列表写入一个文件,但我不知道如何。我必须将这两个对象及其类型写入该链接列表中。我已经创建了以下作为主要类,但我在编写文件部分有问题。你能指导我吗?写入java文件的帮助

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


    } 
} 
+0

这取决于你想要写入文件的内容。你想要的值,serlialised对象,一个XML表示? – Codemwnci 2010-11-15 16:04:30

+0

我想写对象 – 2010-11-15 16:05:52

+0

以可读形式。或以二进制形式? – Codemwnci 2010-11-15 16:08:27

回答

2

java.io.PrintStream

PrintStream p = new PrintStream(fop); 
for (Human h : link) { 
    p.println(h.getType()); 
    p.println(h); 
} 
p.close(); 

假设你已经实施了人类一个toString方法。

1

您的问题一个简单而工作的解决方案将创建一个简单的“CSV”文件,这将是您的Human对象的可读表示,看起来像:

Anna;Student 
Elvis;Instructor 

你可以做实现这一目标:

for (Human h : link) { 
    String line = h.toString() + ";" + h.getType() + "\n"; 
    fop.write(line.getBytes()); 
} 
+0

如果我想在Test类中添加另一个方法来读取'textfile'_which我已经使用上面的code_ino linkedList创建了一个好方法吗? – 2010-11-15 16:33:37