我得到了这个错误:
bill value:$ 0.10
bill value: $0.05
bill value: $0.01
bill value: $100.00
Exception in thread "main" java.io.EOFException
at java.io.ObjectInputStream$BlockDataInputStream.peekByte(Unknown Source)
at java.io.ObjectInputStream.readObject0(Unknown Source)
at java.io.ObjectInputStream.readObject(Unknown Source)
at ReadMoney.main(ReadMoney.java:12)==================我的代码:
//import java.util.Date;
public class ReadMoney
{
public static void main(String argv[]) throws Exception
{
FileInputStream fis = new FileInputStream("money.out");
ObjectInputStream ois = new ObjectInputStream(fis);
Object read;
try
{
while ((read = ois.readObject()) != null)
{
if (read instanceof Bill)
{
System.out.println("bill value: " + read);
}
else if (read instanceof Quarter)
{
}// while
else if (read instanceof Dime)
{
System.out.println("bill value:" + read);
}
else if (read instanceof Nickel)
{
System.out.println("bill value:" + read);
}
else if (read instanceof Penny)
{
System.out.println("bill value:" + read);
}
else if (read instanceof Bill)
{
System.out.println("bill value:" + read );
}
Money quarter = (Money) ois.readObject();
System.out.println("Quarter: "+ quarter);
System.out.println("Quarter: "+ quarter);
Money dime = (Money) ois.readObject();
System.out.println("Dime:" + dime);
Money nickel = (Money)ois.readObject();
System.out.println("Nickel:" + nickel);
Money penny = (Money) ois.readObject();
System.out.println("Penny:" + penny);
Money bill = (Money) ois.readObject();
System.out.println("Bill: " + bill);
}// try
} catch (IllegalBillException ibe)
{
System.out.println("End of file reached");
}
ois.close();
fis.close();
}// main
}// class我非常确定我的try和catch块是正确的,但是我的程序没有打印两个季度的值,而且由于某种奇怪的原因,文本也没有显示“文件末尾到达”。=/
发布于 2011-12-19 05:20:47
您正在捕获IllegalBillException (不管它是什么),但是您没有捕获EOFException (或者它是超类,IOException)。
发布于 2011-12-19 05:55:24
问题在于,使用null检查来测试EOF的while条件并不“保护”"}// try“之后的内容,因此在该点之后的readObject调用将尝试读取EOF之外的内容并获取异常。
你需要以某种方式重组你的逻辑。
捕获EOFException将使异常“消失”,但不会修复您的错误。
https://stackoverflow.com/questions/8554854
复制相似问题