先声明输入流再声明输出流出现java.io.EOFException,但是先声明输出流再声明输入流却不会报错
# 具体遇到的问题
# 报错信息的截图
java.io.EOFException
at java.io.ObjectInputStream$PeekInputStream.readFully(ObjectInputStream.java:2353)
at java.io.ObjectInputStream$BlockDataInputStream.readShort(ObjectInputStream.java:2822)
at java.io.ObjectInputStream.readStreamHeader(ObjectInputStream.java:804)
at java.io.ObjectInputStream.<init>(ObjectInputStream.java:301)
# 相关课程内容截图
# 尝试过的解决思路和结果
FileOutputStream fos = new FileOutputStream("D:\\Product.txt");
ObjectOutputStream oos = new ObjectOutputStream(fos);
FileInputStream fis = new FileInputStream("D:\\Product.txt");
ObjectInputStream ois = new ObjectInputStream(fis);
# 粘贴全部相关代码,切记添加代码注释(请勿截图)
public class Product implements Serializable {
private String id;
private String name;
private String categories;
private double price;
public Product(String id, String name, String categories, double price) {
this.id = id;
this.name = name;
this.categories = categories;
this.price = price;
}
@Override
public String toString() {
return "产品ID:" + id +
"\n产品属性:" + name +
"\n产品属性:" + categories +
"\n产品价格:" + price;
}public static void main(String[] args) {
try {
Product iphone = new Product("123", "iphone", "telephone", 4888.0);
Product ipad = new Product("234", "ipad", "computer", 5088.0);
Product macbook = new Product("345", "macbook", "computer", 10688.0);
Product iwatch = new Product("256", "iwatch", "watch", 4799.0);
FileInputStream fis = new FileInputStream("D:\\Product.txt");
ObjectInputStream ois = new ObjectInputStream(fis);
FileOutputStream fos = new FileOutputStream("D:\\Product.txt");
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(iphone);
oos.writeObject(ipad);
oos.writeObject(macbook);
oos.writeObject(iwatch);
oos.writeObject(null);
oos.flush();
Product product;
while ((product = (Product) ois.readObject()) != null)
System.out.println(product.toString());
oos.close();
fos.close();
ois.close();
fis.close();
} catch (FileNotFoundException e) {
System.out.println("File Not Found...");
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
15
收起
正在回答
1回答
同学你好,老师并没有复现同学的问题,无论是先声明输入流还是先声明流,都可以正确执行,例如:
先声明输出流
先声明输入流
如上所示,都可以正确执行,可能是同学工具的问题,同学尝试重新启动一下自己的eclipse,再来试试。
如果同学使用的不是eclipse,建议同学换成eclipse再来试试。
java工程师2020版
- 参与学习 人
- 提交作业 9393 份
- 解答问题 16556 个
综合就业常年第一,编程排行常年霸榜,无需脱产即可学习,北上广深月薪过万 无论你是未就业的学生还是想转行的在职人员,不需要基础,只要你有梦想,想高薪
了解课程
恭喜解决一个难题,获得1积分~
来为老师/同学的回答评分吧
0 星