课题打卡~请老师检查
来源:5-3 自由编程
慕仙4530950
2020-06-19 18:02:30
//运用了几个方法综合练习
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) {
this.id = id;
this.name = name;
this.categories = categories;
this.price = price;
}
//setter和getter方法
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;
}
@Override
public String toString() {
return "产品ID:" + id + "\n产品名称: " + name + "\n产品属性: " + categories + "\n产品价格:" + price + "元\n";
}
}
//测试类
public class Test{
public static void main(String[] args) {
// 创建Product对象
Product iphone = new Product(123, "iphone", "telephone", 4888);
Product ipad = new Product(234, "ipad", "computer", 5088);
Product macbook = new Product(345, "macbook", "computer", 10688);
Product iwatch = new Product(456, "iwatch", "watch", 4799);
try {
FileOutputStream fos = new FileOutputStream("/Users/mac/Desktop/product.txt");
ObjectOutputStream oos = new ObjectOutputStream(fos);
FileInputStream fis = new FileInputStream("/Users/mac/Desktop/product.txt");
ObjectInputStream ois = new ObjectInputStream(fis);
// 将Product对象写入文件
//第一种方式写入
// oos.writeObject(iphone);
// oos.writeObject(ipad);
// oos.writeObject(macbook);
// oos.writeObject(iwatch);
//第二种方式写入
//运用集合HashSet添加对象
// Set<Product> set = new HashSet<Product>();
// //创建类数组
// Object[] obj = {iphone,ipad,macbook,iwatch};
// for(int i=0;i<obj.length;i++) {
// set.add((Product)obj[i]);
// }
// Iterator it = set.iterator();
// while(it.hasNext()) {
// Product p = (Product) it.next();
// oos.writeObject(p);
// }
//第三种方式写入
//运用集合ArrayList添加对象
List<Product> list = new ArrayList<Product>();
//创建类数组
Object[] obj = {iphone,ipad,macbook,iwatch};
for(int i=0;i<obj.length;i++) {
list.add((Product) obj[i]);
}
for(int i=0;i<list.size();i++) {
oos.writeObject(obj[i]);
}
oos.writeObject(null);
oos.flush();
// 读取对象信息
Product product = null;
try {
while((product = (Product)ois.readObject()) != null) {
System.out.println(product);
}
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
fos.close();
oos.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}1回答
已完成练习,棒棒哒!继续加油!
祝学习愉快!
相似问题