我序列化包含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)
答案 0 :(得分:1)
您已经显示它的应该可以序列化的Statistics类。它实现了Serializable
,其3个字段可以自然序列化。这应该足够了。
我怀疑问题是您实际尝试序列化的类是不同的:
答案 1 :(得分:-1)
我重新安装了最新的jdk,重新编译了代码并重启了几次,现在上面发布的代码正常工作