두 클래스가 모두 변수를 출력하기 위해 toString 재정의를 포함하는 StudentData 객체 (name, Date of Birth, ID)의 배열을 만들도록 설계되었습니다. 그런 다음 배열을 serialize하고 studentdata.txt라는 파일에 저장합니다. 그런 다음 파일에서 배열을 읽고이 데이터에서 새 배열 객체를 재구성하고 배열의 각 항목을 콘솔에 인쇄해야합니다. complie 할 때맞춤 클래스 저장시 NotSerializableException
암 난에 잘 될,
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 메소드를 호출 ...이 오류를 것 점점 각 루프마다 a를 사용해야한다고 가정합니다. 이렇게?
//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();
}
}
}
코드 블록에 일관되고 논리적 인 들여 쓰기를 사용하십시오. –