麻烦老师帮忙看一下这个异常怎么解决?
来源:5-3 自由编程
Michael_2020
2020-03-14 21:53:42
结果正常输出了,好像报了一个老师课程中讲的结尾异常?
请老师帮忙看一下其他代码是否合理,谢谢!
package com.yito.product;
import java.io.Serializable;
public class Product implements Serializable {
private String id;//商品编号
private String name;//商品名称
private String categories;//商品属性
private double price;//商品价格
//构造方法
public Product(){
}
public Product(String id, String name, String categories, double price){
this.setId(id);
this.setName(name);
this.setCategories(categories);
this.setPrice(price);
}
//set/get
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCategories() {
return categories;
}
public void setCategories(String categories) {
this.categories = categories;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
//toString
@Override
public String toString() {
return "产品ID:"+this.getId()+'\n'
+"产品名称:"+this.getName()+'\n'
+"产品属性:"+this.getCategories()+'\n'
+"产品价格:"+this.getPrice();
}
}package com.yito.product;
import java.io.*;
public class Test {
public static void main(String[] args) {
//实现化商品对象并赋值
Product iphone = new Product("123", "iphone","telephone",4888);
Product ipad = new Product("234","ipad","computer",5088);
Product macbook = new Product("345","macbook","computer",10688);
Product iwatch = new Product("256","iwatch","watch",4799);
try {
//创建对象输入输出流
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("Product.txt"));
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("Product.txt"));
//将对象信息写入文件
oos.writeObject(iphone);
oos.writeObject(ipad);
oos.writeObject(macbook);
oos.writeObject(iwatch);
oos.flush();
//读取对象信息
System.out.println("apple系列产品信息:");
Product product =null;
while (( product = (Product) ois.readObject())!=null) {
System.out.println(product);
System.out.println();
}
oos.close();
ois.close();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}1回答
同学,你好!读取数据时默认是不能以null作为文件读取结束的标志的,如果想要以null作为标志,那么在写入数据的时候最后写入null就可以了,添加如下所示选中的代码

如果我的回答解决了你的疑惑,请采纳!祝学习愉快!
相似问题