【发布时间】:2018-11-19 14:12:52
【问题描述】:
一个类将“StudentRecord”数组的一个元素写入它自己的序列化文件中,我已经检查过它是否工作正常;但是,在另一种方法(printstats)中,我使用 ObjectInputStream 的 readin 反序列化文件并转换返回的对象,但未填充 StudentRecord 对象。
package adapter;
import java.io.*;
import model.*;
import util.FileIO;
public abstract class Gradebook implements Gradeable{
private StudentRecord [] sturec;
public Gradebook(String fname) {
FileIO f = new FileIO("C:\\Users\\maya4\\eclipse-workspace\\Lab 5\\StudentInfo.txt");
Student [] stuarr = f.readData();
Statistics statobj = new Statistics(stuarr,f);
//System.out.printf(" main determines that countr holds %d students\n", f.getCountr());
statobj.calculate();
if(DEBUG)
{
statobj.print();
}
for(int i =0 ; i<f.getCountr();i++)
{
sturec = new StudentRecord[40];
sturec[i] = new StudentRecord(statobj, stuarr[i]);
if(DEBUG)
{
sturec[i].printStudentRecord();
}
}
for(int i=0;i<f.getCountr()-1;i++)
{
String tempstring= Integer.toString(stuarr[i].getId());
String filename = tempstring +".dat";
try {
ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(filename));
out.writeObject(sturec[i]);
if (DEBUG)
{
System.out.printf("filename is %s ", filename);
}
}
catch(FileNotFoundException fne)
{
System.out.println("Error--" +fne.toString());
}
catch(IOException ioe)
{
System.out.println("Error" +ioe.toString());
}
}
System.out.println("\n");
}
public void printstats(int stuid)
{
//deserialize any file and print stats.
String Sstuid = Integer.toString(stuid)+".dat";
try
{
if(DEBUG)
{
System.out.printf("filename: %s", Sstuid);
}
//problem area!
ObjectInputStream in = new ObjectInputStream(new FileInputStream(Sstuid));
StudentRecord tempsr= (StudentRecord)in.readObject();
System.out.printf("%d", tempsr.getSt().getId());
//tempsr.printStudentRecord();
}
catch(FileNotFoundException fne)
{
System.out.println("Error--" + fne.toString());
}
catch(IOException ioe)
{
System.out.println("Error --" + ioe.toString());
}
catch (ClassNotFoundException cnf)
{
System.out.println("Error--" + cnf.toString());
}
}
}
【问题讨论】:
-
您忘记关闭
ObjectOutputStream,因此缓冲的数据从未写入文件。 强烈推荐使用try-with-resources。 -
我返回并关闭了 ObjectOutputStream 对象和 ObjectInputStream 对象,但我仍然收到输入 D 的错误:
-
输入有什么错误?您的问题对于实际出了什么问题非常模糊。
-
@Andreas 什么缓冲数据?
ObjectOutputStream和FileOutoutStream都没有被缓冲。 -
抱歉,ObjectInputStream 出现问题 in = new ObjectInputStream(new FileInputStream(Sstuid));因为没有填充 tempsr,所以程序在该行崩溃
标签: java serialization objectinputstream