序列化练习打卡
来源:5-3 自由编程
weixin_慕村4552609
2022-01-12 23:22:54
package com.imooc.io;
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 SerializableTest {
public static void main(String[] args) {
Product iphone = new Product(123, "iphone", "telephone", 4888.0f);
Product ipad = new Product(234, "ipad", "computer", 5088.0f);
Product macbook = new Product(345, "macbook", "computer", 10688.0f);
Product iwatch = new Product(256, "iwatch", "watch", 4799.0f);
try {
FileOutputStream fos = new FileOutputStream("SerializableTest.txt");
ObjectOutputStream obs = new ObjectOutputStream(fos);
obs.writeObject(iphone);
obs.writeObject(ipad);
obs.writeObject(macbook);
obs.writeObject(iwatch);
obs.writeObject(null);
obs.flush();
obs.close();
fos.close();
FileInputStream fis = new FileInputStream("SerializableTest.txt");
ObjectInputStream ois = new ObjectInputStream(fis);
try {
Product product = null;
while ((product = (Product) ois.readObject()) != null) {
System.out.println(product);
System.out.println();
}
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
ois.close();
fis.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
package com.imooc.io;
import java.io.Serializable;
public class Product implements Serializable {
private int id;
private String name;
private String categories;
private float price;
public Product() {
}
public Product(int id, String name, String categories, float price) {
super();
this.id = id;
this.name = name;
this.categories = categories;
this.price = price;
}
@Override
public String toString() {
return "产品ID:" + id + "\n产品名称:" + name + "\n产品属性:" + categories + "\n产品价格:" + 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 float getPrice() {
return price;
}
public void setPrice(float price) {
this.price = price;
}
}1回答
好帮手慕小小
2022-01-13
同学你好,已完成练习,代码逻辑清晰,格式规范,非常好,继续加油!祝学习愉快~
相似问题