2015-10-20 225 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