请老师检查,谢谢
# 具体遇到的问题
# 报错信息的截图
# 相关课程内容截图
# 尝试过的解决思路和结果
# 粘贴全部相关代码,切记添加代码注释(请勿截图)
package com.zhong.serial;
import java.io.Serializable;
public class Product implements Serializable {
private int id;
private String name;
private String categories;
private double price;
public Product(){
}
public Product(int id,String name,String catagories,double price){
this.setId(id);
this.setName(name);
this.setCategories(catagories);
this.setPrice(price);
}
public int getId() {
return id;
}
public void setId(int 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;
}
@Override
public String toString() {
// TODO Auto-generated method stub
return "产品ID:"+this.getId()+"\n产品名称:"+this.getName()+"\n产品属性:"+this.getCategories()+"\n产品价格:"+this.getPrice()+"元\n";
}
}
package com.zhong.serial;
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 ProTest {
public static void main(String[] args) {
// TODO Auto-generated method stub
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 {
FileOutputStream fos=new FileOutputStream("imooc.txt");
ObjectOutputStream oos=new ObjectOutputStream(fos);
FileInputStream fis=new FileInputStream("imooc.txt");
ObjectInputStream ois=new ObjectInputStream(fis);
oos.writeObject(iphone);
oos.writeObject(ipad);
oos.writeObject(macbook);
oos.writeObject(iwatch);
oos.flush();
try {
System.out.println(ois.readObject());
System.out.println(ois.readObject());
System.out.println(ois.readObject());
System.out.println(ois.readObject());
} 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){
e.printStackTrace();
}
}
}
正在回答
同学的代码完成的不错,建议增加finally块,将流的关闭写在finally块中。
- 参与学习 人
- 提交作业 9393 份
- 解答问题 16556 个
综合就业常年第一,编程排行常年霸榜,无需脱产即可学习,北上广深月薪过万 无论你是未就业的学生还是想转行的在职人员,不需要基础,只要你有梦想,想高薪
了解课程
恭喜解决一个难题,获得1积分~
来为老师/同学的回答评分吧
0 星