2012-10-18 2 views
3

두 클래스가 모두 변수를 출력하기 위해 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(); 
       } 

     } 








    } 
+0

코드 블록에 일관되고 논리적 인 들여 쓰기를 사용하십시오. –

답변

1

NotSerializableException: Student 예외를 제거하려면 Student 클래스가 Serializable 인터페이스를 구현하도록하십시오. (.이 마커 인터페이스입니다 있습니다, 그래서 당신은 어떤 방법을 구현할 필요가 없습니다) 반복하려면

class Student implements Serializable { 
} 

를 배열을 SStudent의 객체를,이 시도 :

for (Student st : S) { 
    System.out.println(st); 
} 

배열에 대한 설명이 포함 된 이름을 선택 하겠지만 (students) 배열을

Student[] students = new Student[n]; 

으로 선언하면 for 루프를보다 쉽게 ​​읽을 수 있습니다. 명시 적 유형 Student의 객체에 toString 메소드를 호출 할 필요가 없습니다

for (Student student : students) { 
    System.out.println(student); 
} 

참고. String을 예상하는 메소드에 대한 매개 변수로 오브젝트를 사용할 때 Java는이를 암시 적으로 수행합니다.

+0

감사합니다. 코드를 읽을 수 있도록 가져 오는 것이 얼마나 쉬운 지 알고 있습니다 ... 그러면 누구나 쉽게 사용할 수 있습니다! – Quinn

1

은 Student 클래스 java.io.Serializable 인터페이스를 구현합니다.