5-1编程题
package com.imooc.seria; import java.io.Serializable; public class Produce implements Serializable{ private String id; private String name; private double price; public Produce(String id,String name,double price) { this.id=id; this.name=name; 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 double getPrice() { return price; } public void setPrice(double price) { this.price = price; } @Override public String toString() { return "Produce [id=" + id + ", name=" + name + ", price=" + price + "]"; } }
package com.imooc.seria; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.util.ArrayList; import java.util.List; public class Test { public static void main (String[] args){ Produce p1 = new Produce("s0001", "iphone", 5000); Produce p2 = new Produce("s0002", "ipad", 4000); Produce p3 = new Produce("s0003", "macbook", 3000); Produce p4 = new Produce("s0004", "iwatch", 2000); try { FileOutputStream fos = new FileOutputStream("imooc1.txt"); ObjectOutputStream oos = new ObjectOutputStream(fos); oos.writeObject(p1); oos.writeObject(p2); oos.writeObject(p3); oos.writeObject(p4); oos.flush(); FileInputStream fis = new FileInputStream("imooc1.txt"); ObjectInputStream ois = new ObjectInputStream(fis); List< Produce> produces = new ArrayList<>(); int n = 0; while((n=ois.read())!=-1){ try { produces.add((Produce) ois.readObject()); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } } for(int i =0;i<produces.size();i++){ System.out.println(produces); } fis.close(); ois.close(); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); }catch (IOException e) { e.printStackTrace(); } } }
不能输出四个对象-_-
50
收起
正在回答 回答被采纳积分+1
3回答
Java零基础入门18
- 参与学习 人
- 提交作业 7317 份
- 解答问题 14452 个
想要入门学编程?多年一直活跃在编程语言排行版前列的Java是一个很好的选择。本路径将从Java基础语法、面向对象、常用工具类三部分,为你开启软件开发的大门!
了解课程
恭喜解决一个难题,获得1积分~
来为老师/同学的回答评分吧
0 星