我想用输出语句一次性全部输出,结果出错,只能一次一次输出,为什么?
package com.imooc.name;
import java.io.Serializable;
public class Product implements Serializable{
private int id;
private String name;
private String categories;
private int price;
public Product() {
super();
}
public Product(int id, String name, String categories, int price) {
super();
this.id = id;
this.name = name;
this.categories = categories;
this.price = 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 int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
public String toString() {
return ("产品id:"+this.getId()+"\n产品名称:"+this.getName()+"\n产品属性:"+this.getCategories()+"\n产品价格:"+this.getPrice());
}
}
package com.imooc.name;
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) {
// TODO Auto-generated method stub
Product iphone=new Product(123,"ipone","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 fi=new FileOutputStream("imooc.txt");
ObjectOutputStream ob=new ObjectOutputStream(fi);
FileInputStream fi1=new FileInputStream("imooc.txt");
ObjectInputStream ob1=new ObjectInputStream(fi1);
ob.writeObject(iphone);
ob.writeObject(ipad);
ob.writeObject(macbook);
ob.writeObject(iwatch);
ob.flush();
try {
Product product=(Product)ob1.readObject();
System.out.println(product);
Product product1=(Product)ob1.readObject();
System.out.println("\n"+product1);
Product product2=(Product)ob1.readObject();
System.out.println("\n"+product2);
Product product3=(Product)ob1.readObject();
System.out.println("\n"+product3);
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
正在回答 回答被采纳积分+1
- 参与学习 人
- 提交作业 3802 份
- 解答问题 11489 个
本阶段带你迈入Java世界,学习Java必备基础知识,基础语法、面向对象思想以及常用工具类的使用。
了解课程
恭喜解决一个难题,获得1积分~
来为老师/同学的回答评分吧
0 星