2016-02-13 93 views
-1

Im序列化包含一個Statistics類實例的Student類,這兩個類都實現了Serializable,但是堆棧跟蹤表明這個類不是可序列化的。如果您還有其他問題,請告訴我。是什麼讓這個類不可序列化?

FILENAME.TXT:

Stud Qu1 Qu2 Qu3 Qu4 Qu5 
1234 052 007 100 078 034 
2134 090 036 090 077 030 
3124 100 045 020 090 070 
4532 011 017 081 032 077 
5678 020 012 045 078 034 
6134 034 080 055 078 045 
7874 060 100 056 078 078 
8026 070 010 066 078 056 
9893 034 009 077 078 020 
1947 045 040 088 078 055 
2877 055 050 099 078 080 
3189 022 070 100 078 077 
4602 089 050 091 078 060 
5405 011 011 000 078 010 
6999 000 098 089 078 020 

司機:

package Driver; 
import Model.Statistics; 
import Model.Student; 
import utilities.Util; 
import utilities.Serialization; 

public class Driver { 
    public static final boolean DEBUG_MODE = true; 

    public static void main(String[] args) { 
     Student lab2[] = new Student[40]; 
     // Populate the student array by reading from file 
     lab2 = Util.readFile("E:\\CIS35A\\Assignment 6\\src\\filename.txt", lab2); 
     Statistics statlab2 = new Statistics(); 

     // Calculate the quiz stats 
     statlab2.findLow(lab2); 
     statlab2.findHigh(lab2); 
     statlab2.findAvg(lab2); 

     // create a file for each student via serialization 
     for(int i = 0; i < lab2.length; i++){ 
      lab2[i].setClassStats(statlab2); // <---- if i comment this out it runs, but why? also I need it to store that data before serialization. 
      Serialization.serialize(new String("Student")+ 
        ((Integer)i).toString()+ 
        new String(".stu"), lab2[i]); 
     } 

     if(DEBUG_MODE){ 

     } 
    } 

} 

的Util類:

package utilities; 
import java.io.BufferedReader; 
import java.io.FileReader; 
import java.io.IOException; 
import java.util.StringTokenizer; 

import Model.Student; 

public class Util { 
    public static Student[] readFile(String filename, Student[] stu) { 
     // Reads the file and builds student array. 

     int studentCounter = -99;//init to a value I know is out of bounds 
     try { 
      // Open the file using FileReader Object. 
      FileReader file = new FileReader(filename); 

      // load the file into a buffer 
      BufferedReader fileBuff = new BufferedReader(file); 

      // In a loop read a line using readLine method. 
      boolean eof = false; 
      studentCounter = -1;//set to -1 because the first line is the table headings 
      while (!eof) { 
       String line = fileBuff.readLine(); 
       if (line == null){ 
        eof = true; 
        continue; 
       } 
       else if(studentCounter >= 0){ 
        // Tokenize each line using StringTokenizer Object 
        StringTokenizer st = new StringTokenizer(line); 

        // Create the Student 
        stu[studentCounter] = new Student(); 

        int quizCounter = -1;// init to -1 because the first token 
             // is not going to be a quiz score 
        while (st.hasMoreTokens()) { 
         String currentToken = st.nextToken(); 

         // Each token is converted from String to Integer using parseInt method 
         int value = Integer.parseInt(currentToken); 

         // Value is then saved in the right property of Student Object. 
         if(quizCounter == -1){ 
          // Store the student ID in the student instance we created 
          stu[studentCounter].setSID(value); 
         } 
         else{ 
          // Store the quiz grades in the students score list 
          stu[studentCounter].setScore(value, quizCounter); 
         } 
         quizCounter++; 
        } 
       } 
       studentCounter++; 
      } 
      fileBuff.close(); 




     } catch (IOException e) { 
      System.out.println(e.toString()); 
      e.printStackTrace(); 
     } 

     return trimArray(stu, studentCounter); 
    } 

    /* 
    * this method is used for shortening the 
    * array to the number of elements used 
    * */ 
    private static Student[] trimArray(Student[] arr, int count){ 
     Student[] newArr = new Student[count]; 
     for(int i = 0; i < count; i++){ 
      newArr[i] = arr[i]; 
     } 
     return newArr; 
    } 
} 

序列化類別:

package utilities; 

import java.io.FileInputStream; 
import java.io.FileOutputStream; 
import java.io.IOException; 
import java.io.ObjectInputStream; 
import java.io.ObjectOutputStream; 

public class Serialization { 
    /* 
    * This method will serialize any object and store it in a file with the 
    * filename provided and return true if successful 
    * */ 
    public static boolean serialize(String filename, Object obj){ 
     try { 
      ObjectOutputStream serializer = new ObjectOutputStream(new FileOutputStream(filename)); 
      serializer.writeObject(obj); 
      serializer.close(); 
      if(true){ 
       System.out.println("sucesss!!!!!!!!!"); 
      } 

     } catch (IOException e) { 
      e.printStackTrace(); 
      return false; 
     } 
     return true; 
    } 
    /* 
    * This method will take any serialized object from a file with the 
    * filename provided and return the object or null 
    * */ 
    public static Object deSerialize(String filename){ 
     try { 
      ObjectInputStream deSerializer = new ObjectInputStream(
               new FileInputStream(filename)); 
      Object data = deSerializer.readObject(); 
      deSerializer.close(); 
      return data; 
     } catch (IOException | ClassNotFoundException e) { 
      e.printStackTrace(); 
      return null; 
     } 

    } 
} 

學生類別:

package Model; 

import java.io.Serializable; 

public class Student implements Serializable{ 
    private int SID; 
    private int scores[] = new int[5]; 
    private Statistics classStats; 

    // Setters and Getters 
    public int getSID() { 
     return SID; 
    } 

    public void setSID(int sID) { 
     SID = sID; 
    } 

    public int[] getScores() { 
     return scores; 
    } 
    public int getScore(int index) { 
     return scores[index]; 
    } 

    public void setScores(int[] scores) { 
     this.scores = scores; 
    } 
    public void setScore(int score, int index) { 
     this.scores[index] = score; 
    } 

    public Statistics getClassStats() { 
     return classStats; 
    } 

    public void setClassStats(Statistics classStats) { 
     this.classStats = classStats; 
    } 

    // Methods for printing quiz scores and student ID 
    public void printScores(){ 
     System.out.printf("------- Quiz Scores ------- %n"); 
     for(int i = 0; i < scores.length; i++){ 
      System.out.printf("Quiz %d: %d %n", i+1, scores[i]); 
     } 
     System.out.printf("----- End Quiz Scores ----- %n"); 
    } 

    public void printStudentID(){ 
     System.out.printf("Student ID: %d %n", SID); 
    } 


} 

統計類:

package Model; 

import java.io.Serializable; 

public class Statistics implements Serializable{ 
    private int[] lowScores = new int[5]; 
    private int[] highScores = new int[5]; 
    private float[] avgScores = new float[5]; 

    public void findLow(Student[] studs) { 
     /* 
     * This method will find the lowest score and store it in an array named 
     * lowscores. 
     */ 
     for(int i = 0; i< lowScores.length; i++){ 
      int current = 919; 
      for(int j = 0; j< studs.length; j++){ 
       if(studs[j].getScore(i) < current){ 
        current = studs[j].getScore(i); 
       } 
      } 
      lowScores[i] = current; 
     } 
    } 

    public void findHigh(Student[] studs) { 
     /* 
     * This method will find the highest score and store it in an array 
     * named highscores. 
     */ 

     for(int i = 0; i< highScores.length; i++){ 
      int current = -99; 
      for(int j = 0; j< studs.length; j++){ 
       if(studs[j].getScore(i) > current){ 
        current = studs[j].getScore(i); 
       } 
      } 
      highScores[i] = current; 
     } 
    } 

    public void findAvg(Student[] studs) { 
     /* 
     * This method will find avg score for each quiz and store it in an 
     * array named avgscores. 
     */ 

     for(int i = 0; i< avgScores.length; i++){ 
      float total = 0; 
      for(int j = 0; j< studs.length; j++){ 
       total += studs[j].getScore(i); 
      } 
      avgScores[i] = total/studs.length; 
     } 
    } 

    // Methods for printing the highs, lows, and average scores for each quiz 
    public void printHighScores(){ 
     System.out.printf("------- High Scores ------- %n"); 
     for(int i = 0; i < highScores.length; i++){ 
      System.out.printf("Quiz %d: %d %n", i+1, highScores[i]); 
     } 
     System.out.printf("----- End High Scores ----- %n"); 
    } 

    public void printLowScores(){ 
     System.out.printf("------- Low Scores ------- %n"); 
     for(int i = 0; i < lowScores.length; i++){ 
      System.out.printf("Quiz %d: %d %n", i+1, lowScores[i]); 
     } 
     System.out.printf("----- End Low Scores ----- %n"); 
    } 

    public void printAvgScores(){ 
     System.out.printf("------- Average Scores ------- %n"); 
     for(int i = 0; i < avgScores.length; i++){ 
      System.out.printf("Quiz %d: %f %n", i+1, avgScores[i]); 
     } 
     System.out.printf("----- End Average Scores ----- %n"); 
    } 
} 

堆棧跟蹤:

java.io.NotSerializableException: Model.Statistics 
    at java.io.ObjectOutputStream.writeObject0(Unknown Source) 
    at java.io.ObjectOutputStream.defaultWriteFields(Unknown Source) 
    at java.io.ObjectOutputStream.writeSerialData(Unknown Source) 
    at java.io.ObjectOutputStream.writeOrdinaryObject(Unknown Source) 
    at java.io.ObjectOutputStream.writeObject0(Unknown Source) 
    at java.io.ObjectOutputStream.writeObject(Unknown Source) 
    at utilities.Serialization.serialize(Serialization.java:18) 
    at Driver.Driver.main(Driver.java:24) 
+1

您不提供足夠的信息來重現該問題... – alfasin

+0

足夠的信息? – coderguy22296

+0

不需要。您需要顯示堆棧跟蹤。不是Serializable的實際類在異常中被命名。 – EJP

回答

1

因爲你已經表明,它應該序列化的統計類。它實現了Serializable,它的3個字段本地可序列化。這應該足夠了。

我懷疑,問題是,你實際上是試圖序列化類是不同的:

  • 您可以向我們展示了源代碼的版本錯誤
  • 類可能需要重新編譯
  • 一個JAR文件可能需要重建
  • JAR文件可能需要重新部署
+0

多數民衆贊成在我的想法,但我只是發現了一些有趣的事情。當我在Driver中註釋掉這一行時,它會毫無例外地執行:「lab2 [i] .setClassStats(statlab2);」 。然後我嘗試在Student類(統計classStats = new Statistics;)中創建一個統計實例,而不是「Statistics classStats;」即使驅動程序中的行被註釋掉,也會觸發異常。 – coderguy22296

+0

即時嘗試序列化學生類,其中包含一個實例的統計類是造成麻煩,不知道爲什麼。我向你保證,這是產生我的問題的源代碼。 – coderguy22296

+2

@ coderguy22296我向你保證它不是。 – EJP

-1

我重新安裝最新的jdk,重新編譯的代碼,並重新啓動幾次,現在上面的代碼工作

+0

這是必要的唯一部分是重新編譯。 – EJP

相關問題