gpt4 book ai didi

java - 如何从文件中反序列化多个对象

转载 作者:行者123 更新时间:2023-12-01 11:21:48 25 4
gpt4 key购买 nike

如何从文件中反序列化多个对象?以下是我尝试过的代码,它适用于一个对象,但不适用于多个对象。

         public List<Show> populateDataFromFile(String fileName) {
// TODO Auto-generated method stub
Show s = null;
//FileInputStream fileIn=null;

try
{
FileInputStream fileIn=new FileInputStream("C:\\Users\\Admin\\Desktop\\Participant_Workspace\\Q1\\ShowBookingSystem\\ShowDetails.ser");
int i=0;
while((i=fileIn.read())!=-1){
// fileIn = new FileInputStream("C:\\Users\\Admin\\Desktop\\Participant_Workspace\\Q1\\ShowBookingSystem\\ShowDetails.ser");
ObjectInputStream in = new ObjectInputStream(fileIn);

s = (Show) in.readObject();
in.close();
fileIn.close();

System.out.println("Name: " + s.getShowName());
System.out.println("Show Time: " + s.getShowTime());
System.out.println("Seats Available: " + s.getSeatsAvailable());
}
}catch(IOException i)
{
i.printStackTrace();

}catch(ClassNotFoundException c)
{
System.out.println("Employee class not found");
c.printStackTrace();

}

return null;
}

我什至尝试使用

while((i=fin.read())!=-1) 

但是没有成功。我需要做出什么改变?

最佳答案

试试这个方法:

 Show s = null;
try {
FileInputStream fileIn = new FileInputStream(".....");
ObjectInputStream in = new ObjectInputStream(fileIn);
while (true) {
try {
s = (Show) in.readObject();
} catch (IOException ex) {
break;
} catch (ClassNotFoundException ex) {
Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
}

System.out.println("Name: " + s.getShowName());
System.out.println("Show Time: " + s.getShowTime());
System.out.println("Seats Available: " + s.getSeatsAvailable());
}

in.close();
fileIn.close();

关于java - 如何从文件中反序列化多个对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31140266/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com