老师您看我这个写的符合要求吗?
//Product package Homework5_3; import java.io.Serializable; public class Product implements Serializable { private String id; private String name; private String categories; private double price; public Product() { } @Override public String toString() { return "产品ID:"+id+"\n产品名称:"+name+"\n产品属性:"+categories+"\n产品价格:"+price; } public Product(String id, String name, String categories, double price) { this.id = id; this.name = name; this.categories = categories; this.price = price; } 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; } } //Test package Homework5_3; 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 Test { public static void main(String[] args) { Product iphone = new Product("123", "iphone", "telephone", 4888.0); Product ipad = new Product("234", "ipad", "computer", 5088.0); Product macbook = new Product("456", "macbook", "computer", 10688.0); Product iwatch = new Product("256", "iwatch", "watch", 4799.0); try { FileOutputStream fos = new FileOutputStream("apple.txt"); ObjectOutputStream oos = new ObjectOutputStream(fos); FileInputStream fis = new FileInputStream("apple.txt"); ObjectInputStream ois = new ObjectInputStream(fis); oos.writeObject(iphone); oos.writeObject(ipad); oos.writeObject(macbook); oos.writeObject(iwatch); oos.writeObject(null); oos.flush(); oos.close(); fos.close(); Product temp = null; System.out.println("Apple产品信息:"); while ((temp = (Product) ois.readObject()) != null) { System.out.println("\n"+temp); } ois.close(); fis.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } } }
0
收起
正在回答 回答被采纳积分+1
2回答
chrismorgen
2018-08-31 18:36:13
效果完成的不错,不过建议你将io流的关闭写在finally代码块中,这样即使发生异常也可以将流关闭。祝学习愉快~
Java零基础入门18
- 参与学习 人
- 提交作业 7317 份
- 解答问题 14452 个
想要入门学编程?多年一直活跃在编程语言排行版前列的Java是一个很好的选择。本路径将从Java基础语法、面向对象、常用工具类三部分,为你开启软件开发的大门!
了解课程
恭喜解决一个难题,获得1积分~
来为老师/同学的回答评分吧
0 星