我的两个类被设计成创建一个 StudentData 对象数组(姓名、出生日期和 ID),其中包括一个 toString 覆盖以打印出所有变量。然后它序列化该数组并将其保存到一个名为 studentdata.txt 的文件中。然后它应该从文件中读取数组并从该数据中重建一个新的数组对象,并将数组中的每个项目打印到控制台。
尝试遵守时出现此错误...
Exception in thread "main" java.io.NotSerializableException: Student
at java.io.ObjectOutputStream.writeObject0(Unknown Source)
at java.io.ObjectOutputStream.writeArray(Unknown Source)
at java.io.ObjectOutputStream.writeObject0(Unknown Source)
at java.io.ObjectOutputStream.writeObject(Unknown Source)
at StudentData.main(StudentData.java:38)
也不确定如何正确循环遍历我的数组并调用我的 toString 方法以打印到控制台,我是否应该假设我应该为每个循环使用一个?像这样?
//for (Student s : ???) {
//System.out.println(How do I call toString from here?);
我的课程
import java.io.*; //importing input-output files
class Student
{
String name; //declaration of variables
String DOB;
int id;
Student(String naam,int idno, String dob) //Initialising variables to user data
{
name=naam;
id=idno;
DOB=dob;
}
public String toString() {
return name+"\t"+id+"\t"+DOB+"\t";
}
}
2号
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
class StudentData //main class
{
public static void main(String args[]) throws IOException //exception handling
{
System.out.println("Enter the numbers of students:");
BufferedReader in=new BufferedReader(new InputStreamReader(System.in));
int n=Integer.parseInt(in.readLine());
Student[] S=new Student[n]; // array of objects declared and defined
for (int i = 0; i < S.length; i++) {
System.out.println("Enter the Details of Student no: "+(i+1)); //reading data form the user
System.out.println("Name: ");
String naam=in.readLine();
System.out.println("ID no: ");
int idno=Integer.parseInt(in.readLine());
System.out.println("DOB: ");
String dob=(in.readLine());
S[i]=new Student(naam,idno,dob);
File studentFile = new File("StudentData.txt");
try {
FileOutputStream fileOutput = new FileOutputStream(studentFile);
ObjectOutputStream objectOutput = new ObjectOutputStream(fileOutput);
objectOutput.writeObject(S);
S = null;
FileInputStream fileInput = new FileInputStream(studentFile);
ObjectInputStream objectInputStream = new ObjectInputStream(fileInput);
S = (Student[]) objectInputStream.readObject();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
//for (Student s : ???) {
//System.out.println();
}
}
}