我已经成功地序列化了对象,当文件被保存时,它们被赋予一个文件名,这是所选择的团队名称。这很好用。但是,当我尝试对文件进行反序列化时,我得到一个FileNotFound
异常,并且它正在寻找一个名为null.ser的文件,该文件并不存在。
然而我的String" fileName"当我刚刚保存它时,显示文件的正确名称,即Arsenal.ser。实际上我可以看到一个名为Arsenal.ser的文件,它包含足够的字节来表明该文件已成功序列化。
下面是一些代码片段,我已经在网上搜索了一个解决方案。我认为这是我使用return
声明的方式吗?请不要建议批发更改,我正在学习!我只想了解为什么它指向null,而不是我保存的文件。
public class WriteClub{
public String tryWriteClub(ClubInfo club){
String fileName = "/home/cg/root/" + club.teamName + ".ser";
try{
FileOutputStream fileOut = new FileOutputStream(fileName);
ObjectOutputStream out = new ObjectOutputStream(fileOut);
out.writeObject(club);
System.out.println("Serialized data is saved in" + fileName);
System.out.println("Filename is" + fileName);
}catch(IOException i)
{
i.printStackTrace();
}
return fileName;
}
}
public class Serializer extends WriteClub
{
public void Serialize()
{
MainMenu pass_choice = new MainMenu();
int passed_choice = pass_choice.chooseTeam();
if(passed_choice==1){
ClubInfo club = new ClubInfo("Arsenal" , "Emirates" , "Premier League" , 11122333 , 60000);
tryWriteClub(club);
} // end if 1
public class DeSerializer
{
public void DeSerialize(String fileName)
{
String fN = fileName;
ClubInfo club;
System.out.println("File name is:" + fN);
try
{
FileInputStream fileIn = new FileInputStream("/home/cg/root/" + fileName + ".ser");
ObjectInputStream in = new ObjectInputStream(fileIn);
club = (ClubInfo) in.readObject();
in.close();
fileIn.close();
}catch(IOException i)
{
i.printStackTrace();
return;
}catch(ClassNotFoundException c)
{
System.out.println("Club class not found");
c.printStackTrace();
return;
}
System.out.println("Saved game loaded...");
System.out.println("Name: " + club.teamName);
System.out.println("Stadium: " + club.stadium);
System.out.println("Division: " + club.division);
// System.out.println("SSN: " + club.SSN);
System.out.println("Stadium Capacity: " + club.stadiumCapacity);
}
}
调用我的DeSerialize方法
case 3:
DeSerializer load = new DeSerializer();
load.DeSerialize(fileName);
exit = true;
break;