2014-01-17 17 views
0
public class Student { 
    String name; 
    int id; 
    float grade;} 

public class UndergraduateStudent extends Student{ 
     float grade2;} 


public class GraduateStudent extends Student{ 
     float grade2,grade3; 
     String supervizor;} 

所以我有基本的类学生被延长到2个types.All的Student对象存储在一个SLL,现在我必须将它们存储到我可以将它们存储在文件中,如果当file.How从列表中提取一个演员到(Student)完成?我将需要从文件中取回它们,那么如何知道文件中每行的类型是什么类型的学生?(我现在对序列化不感兴趣)要归档的对象:如何?

+12

“我现在没有兴趣在序列化” - 是的,你是。您正在讨论将对象存储在文件中。 *是*序列化。 –

+0

你必须使用序列化。 http://www.thejavageek.com/2013/09/08/reading-writing-objects-using-serialization/ –

+0

@JonSkeet我需要“一种方法来保存学生列表到 文本文件”,并在之后我这样做是为了序列化的要求 – Matt

回答

0

您可以将对象转换为xml并从那里让你的对象回来。 也许你可以使用XStream

2
FileOutputStream fos = new FileOutputStream("file.ext"); 
ObjectOutputStream oos = new ObjectOutputStream(fos); 
oos.writeObject(student); 
oos.close(); 

或者只需保存这个对象像纯文本文件(如CSV)

John, 102, 4.5 
Mark, 103, 2.0 
0

你必须让你的类序列化

public class Student implements java.io.Serializable 

阅读文章 - Java Serialization

0

我正在寻找的东西是这样的:

public void writeTofile() throws IOException{ 

    File file = new File("./StudentRepo.txt"); 
    if (!file.exists()) 
     file.createNewFile(); 
    FileWriter fw = new FileWriter(file.getAbsoluteFile()); 
     BufferedWriter bw = new BufferedWriter(fw); 

     Student[] copy = this.getStudents(); 
     for (Student st : copy){ 
      bw.write(st.toString() + "\n"); 
     } 
     bw.close(); 
}