请问老师运行后出现的EOFException异常怎么处理?顺便问一下输入输出流的关闭有先后顺序吗?
来源:5-3 自由编程
慕设计7678942
2020-06-24 23:33:55
package com.imooc.p;
import java.io.Serializable;
public class Product implements Serializable {
// 属性(Attribute)
private String id;
private String name;
private String catrgories;
private double price;
// 无参构造方法
public Product() {
}
// 带参构造方法,并对所有属性赋值
public Product(String id, String name, String categories, double price) {
this.setId(id);
this.setName(name);
this.setCatrgories(categories);
this.setPrice(price);
}
// getter setter
public void setId(String id) {
this.id = id;
}
public String getId() {
return id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCatrgories() {
return catrgories;
}
public void setCatrgories(String catrgories) {
this.catrgories = catrgories;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public String toString() {
return "产品ID: " + this.getId() + "\n产品名称: " + this.getName() + "\n产品属性: " + this.getCatrgories() + "\n产品价格: "
+ this.getPrice()+"元\n";
}
}
==============================
package com.imooc.p;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
public class ProductTest {
public static void main(String[] args) {
// 定义Product类的对象
Product iphone = new Product("123", "iphone", "telephone", 4888.0);
Product ipad = new Product("234", "iapd", "computer", 5088.0);
Product macbook = new Product("345", "macbook", "computer", 10688.0);
Product iwatch = new Product("256", "iwatch", "watch", 4799.0);
try {
FileOutputStream fos = new FileOutputStream("D:\\File\\Product.txt");
ObjectOutputStream oos = new ObjectOutputStream(fos);
FileInputStream fis = new FileInputStream("D:\\File\\Product.txt");
ObjectInputStream ois = new ObjectInputStream(fis);
oos.writeObject(iphone);
oos.writeObject(ipad);
oos.writeObject(macbook);
oos.writeObject(iwatch);
oos.flush();
System.out.println("apple系列产品信息: ");
try {
Product product;
while ((product= (Product) ois.readObject())!=null) {
System.out.println(product);
}
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
fos.close();
oos.close();
fis.close();
ois.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
1回答
同学你好,
1、EOFException异常是因为当读取过程中意外到达文件或流的末尾时,会抛出此IO异常。建议同学在写入文件后,加一句oos.writeObject(null);表示到了文件末尾,如下:

2、输入输出流的关闭有先后顺序。一般情况下,先打开的流后关闭,后打开的流先关闭。
如果我的回答解决了你的疑惑,请采纳!祝学习愉快!
相似问题