5-3自由编程作业,请老师指正
来源:5-3 自由编程
csm032
2019-12-27 20:32:18
package com.imooc.file;
import java.io.Serializable;
public class Product implements Serializable {
private String id;
private String name;
private String categories;
private double price;
public Product() {
}
public Product(String id, String name, String categories, double price) {
this.setId(id);
this.setName(name);
this.setCategories(categories);
this.setPrice(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;
}
@Override
public String toString() {
String str = "产品ID:" + this.getId() + "\n产品名称:" + this.getName() + "\n产品属性:" + this.getCategories() + "\n产品价格:"
+ this.getPrice() + "元";
return str;
}
}
package com.imooc.file;
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[] product = new Product[4];
product[0] = new Product("123", "iphone", "telephone", 4888);
product[1] = new Product("234", "ipad", "computer", 5088.0);
product[2] = new Product("345", "macbook", "computer", 10688);
product[3] = new Product("256", "iwatch", "watch", 4799);
// Product iphone = new Product("123", "iphone", "telephone", 4888);
// Product ipad = new Product("234", "ipad", "tcomputer", 5088.0);
// Product macbook = new Product("345", "macbook", "computer", 10688);
// Product iwatch = new Product("256", "iwatch", "watch", 4799);
try {
FileOutputStream fos = new FileOutputStream("product.txt");
ObjectOutputStream oos = new ObjectOutputStream(fos);
FileInputStream fis = new FileInputStream("product.txt");
ObjectInputStream ois = new ObjectInputStream(fis);
for (int i = 0; i < product.length; i++) {
oos.writeObject(product[i]);
}
oos.flush();
System.out.println("apple系列产品信息");
for (int i = 0; i < product.length; i++) {
Product product1 = null;
try {
product1 = (Product) ois.readObject();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(product1);
System.out.println();
}
fos.close();
oos.close();
fis.close();
ois.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
1回答
好帮手慕酷酷
2019-12-28
同学你好,代码完成的不错!继续努力!
如果我的回答解决了你的疑惑,请采纳!祝学习愉快!
相似问题