【发布时间】:2014-06-20 13:33:35
【问题描述】:
这是一种从包含 Show 类型的序列化对象的 .ser 文件中读取节目详细信息的方法。该方法成功返回列表,但之前给出了异常。为什么会这样,我该如何摆脱它?
public List<Show> populateDataFromFile(String fileName) {
List<Show> shows=new ArrayList<Show>();
ObjectInputStream obj=null;
try {
FileInputStream fin=new FileInputStream(fileName);
obj=new ObjectInputStream(fin);
Show show=null;
while((show=(Show) obj.readObject())!=null)
{
shows.add(show);
show.getShowName();
}
System.out.println(shows);
} catch (IOException e) {
e.printStackTrace();
}catch(ClassNotFoundException e)
{
e.printStackTrace();
}finally
{
try {
obj.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return shows;
}
输出是
java.io.EOFException
at java.io.ObjectInputStream$BlockDataInputStream.peekByte(ObjectInputStream.java:2571)
at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1315)
at java.io.ObjectInputStream.readObject(ObjectInputStream.java:369)
at com.util.DataManagerImpl.populateDataFromFile(DataManagerImpl.java:23)
at com.psl.Client.main(Client.java:9)
Show Name: Sahi re Sahi
Show Time: 6:30 PM
Seats Available: 40
Show Name: Ek Shyam Aapke Naam
Show Time: 6:30 PM
Seats Available: 40
Show Name: Moruchi Maushi
Show Time: 6:30 PM
Seats Available: 40
Show Name: All The Best
Show Time: 6:30 PM
Seats Available: 40
Show Name: Naksharanche Dene
Show Time: 6:30 PM
Seats Available: 40
主要方法是
public static void main(String[] args) {
DataManager dm=new DataManagerImpl();
List<Show>shows=dm.populateDataFromFile("ShowDetails.ser");
// Call all the functionalities from here to test your code.
for(Show show:shows)
{
System.out.println("Show Name: "+show.getShowName());
System.out.println("Show Time: "+show.getShowTime());
System.out.println("Seats Available: "+show.getSeatsAvailable());
}
}
【问题讨论】:
-
无论如何都会返回列表,因为异常被捕获,因此不会停止方法的执行,它会正常返回。现在,如果某些数据已添加到列表中,这些数据将被返回
-
这是有道理的,但是即使在摆脱了 finally 块并在 while 循环之后关闭流之后,我也会遇到同样的错误。