5-3自由编程 交作业
来源:5-3 自由编程
慕的地2082093
2019-10-25 12:38:40
package it.immoc.com;
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 categories, double 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 double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public String toString(){
return "产品ID:"+id+"\n产品名称:"+name+"\n产品属性:"+categories+"\n产品价格:"
+price;
}
}
package it.immoc.com;
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 p1=new Product(123,"iphone","telephone",4888);
Product p2=new Product(234,"ipad","computer",5088);
Product p3=new Product(345,"macbook","computer",10688);
Product p4=new Product(256,"iphone","iwatch",4799);
try {
FileOutputStream fos = new FileOutputStream("hello.txt");
ObjectOutputStream oos=new ObjectOutputStream(fos);
FileInputStream fis=new FileInputStream("hello.txt");
ObjectInputStream ois=new ObjectInputStream(fis);
oos.writeObject(p1);
oos.writeObject(p2);
oos.writeObject(p3);
oos.writeObject(p4);
oos.flush();
try {
for(int i=0;i<4;i++){
Product p=(Product)ois.readObject();
System.out.println(p);
}
} catch (ClassNotFoundException 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回答
好帮手慕酷酷
2019-10-25
同学你好,代码编写的不错,但是有一个小问题,同学在使用完流后,忘记关闭流啦~如果不关闭流,则会导致一直占用系统内存,消耗资源。建议使用完流后调用close()方法。
另外,流关闭的顺序:建议在关闭流时,先打开的后关闭,后打开的先关闭。就比如我们进行开门时,从大门打开,然后打开卧室门,进入房间,出去时,在我们进行关门时,就要先关卧室门,再关大门。
具体如下:
如果我的回答解决了你的疑惑,请采纳!祝学习愉快!
相似问题