练习打卡,请老师检查~
来源:5-3 自由编程
Heijyu
2020-06-21 14:42:07
package com.imooc.io_product_exercise5_3;
import java.io.Serializable;
public class Product implements Serializable {
private int id;
private String name;
private String categories;
private double price;
public Product() {
this(0,null,null,0);
}
public Product(int id, String name, String categories, double price) {
this.setId(id);
this.setName(name);
this.setCategories(categories);
this.setPrice(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;
}
@Override
public String toString() {
return "\nID:" + id + "\nNAME:" + name + "\nCATEGORIES:" + categories + "\nPRICE:" + price;
}
}
package com.imooc.io_product_exercise5_3;
import java.io.EOFException;
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 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(256, "iwatch", "watch", 4799);
try {
FileOutputStream fos = new FileOutputStream("imooc3.txt");
ObjectOutputStream oos = new ObjectOutputStream(fos);
FileInputStream fis = new FileInputStream("imooc3.txt");
ObjectInputStream ois = new ObjectInputStream(fis);
oos.writeObject(iphone);
oos.writeObject(ipad);
oos.writeObject(macbook);
oos.writeObject(iwatch);
oos.writeObject(null);
oos.flush();
Product products;
System.out.println("Apple Products introduction:");
while ((products = (Product) ois.readObject()) != null) {
System.out.println(products);
}
fos.close();
oos.close();
fis.close();
ois.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}1回答
已完成练习,棒棒哒!继续加油!祝学习愉快!
相似问题