一个类将一个" 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());
}
}
}
发布于 2018-06-10 07:07:10
如果,你仍然没有澄清这一点,程序会崩溃,并在下面的代码行显示NPE:
System.out.printf("%d", tempsr.getSt().getId());
以下任一项:
tempsr
is null.tempsr.getSt()
返回null。(1)如果你用writeObject()
写了一个null,会发生(1),你可以在写东西的地方检查。
(2)如果底层属性是(a) null,(b) transient
,或(c) static
:或者,例如,如果没有底层属性,如果方法以某种方式计算了null,就会发生这种情况。
https://stackoverflow.com/questions/50778895
复制相似问题