打卡,老师看看还有什么需要改的地方吗?
来源:5-3 自由编程
谁叫我这么坏
2020-10-17 17:53:11
package onlytest;
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.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;
}
public String toString() {
return "产品ID:" + this.getId() + "\n产品名称:" + this.getName() + "\n产品属性:" + this.getCategories() + "\n产品价格:"
+ this.getPrice() + "元\n";
}
}
package onlytest; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutput; import java.io.ObjectOutputStream; public class ProductTest { public static void main(String[] args) { Product iphone = new Product(123, "iphone", "telephone", 4888.0); Product ipad = new Product(234, "ipad", "computer", 5088.0); Product macbook = new Product(345, "macbook", "computer", 10688.0); Product iwatch = new Product(256, "iwatch", "watch", 4799.0); try { FileOutputStream fos = new FileOutputStream("apple.txt"); FileInputStream fis = new FileInputStream("apple.txt"); ObjectOutputStream oos = new ObjectOutputStream(fos); oos.writeObject(iphone); oos.writeObject(ipad); oos.writeObject(macbook); oos.writeObject(iwatch); oos.writeObject(null); oos.flush(); oos.close(); fos.close(); ObjectInputStream ois = new ObjectInputStream(fis); Product product = null; while ((product = (Product) ois.readObject()) != null) { System.out.println(product); } ois.close(); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
1回答
同学的代码完成的不错,不用修改了,继续加油,祝学习愉快
相似问题
回答 1
回答 1