2015-10-20 228 views
0

我有一个关于我正在处理的数据结构的项目。我有一个LinkedList,我需要能够将对象数据保存到文本文件中将java对象写入CSV文件

“创建一个文本文件,它是姓氏,名字和电子邮件地址的列表。您可以使用CSV或任何其他分隔符“

当我尝试保存对象数据我得到这个‘¬í牛逼约翰’,而不仅仅是‘约翰’

我的类(主要和学生,和电子邮件)实现Serializable

public class Main implements Serializable 
{ 
    public static void main(String[] args) throws IOException 
    { 
    Date date = new Date(); 

    Email e1 = new Email("[email protected]"); 
    Email e2 = new Email("[email protected]"); 
    Email e3 = new Email("[email protected]"); 
    Student s1 = new Student("John", "Snow", e1); 
    Student s2 = new Student("Shiba", "Inu", e2); 
    Student s3 = new Student("Vern", "Vern", e3); 
    Student s4 = new Student("Professor", "Messer", new Email("[email protected]")); 
    ListInterface<Student> linkedList = new LinkedList<Student>(); 
    linkedList.add(s1, 2); //should be pos 3 
    linkedList.add(s2, 3); //should be pos 4 
    linkedList.add(s3, 1); // should be pos 2 
    linkedList.add(s4, 1); //should be pos 1 
    System.out.println(linkedList); 
    try 
    { 
     FileOutputStream fos = new FileOutputStream("students.txt"); 
     ObjectOutputStream output = new ObjectOutputStream(fos); 
     output.writeObject(s1.getfirstName()); 
     output.close(); 
     fos.close(); 
     System.out.println("Data saved in /file/students.txt"); 
    } 
    catch (IOException exc) 
     { 
     System.out.println("Failed to write to file!"); 
     exc.printStackTrace(); 
     } 
    } 
} 

谢谢!

+1

简短的回答是,你不想使用'ObjectOutputStream' –

+0

这是20分钟内该csv话题的第二个问题。是否有主要作业或测试运行? – AlexWien

回答

0

如果你想写入CSV文件,那么你不需要实现Serializable接口。使用序列化,您不能编写csv文件。序列化过程将对象状态写入。 sar文件。你可以考虑使用一些CSV库,或者你可以写它。您可以检查this tutorial