importjava.io.Serializable;publicclassProductimplementsSerializable{//成员属性:产品IDid、产品名称name、产品属性categories、产品价格priceprivateintid;privateStringname;pr...
import java.io.Serializable;
public class Product implements Serializable {
//成员属性:产品ID id、产品名称 name、产品属性 categories、产品价格 price
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.setId(id);
this.setName(name);
this.setCategories(categories);
this.setPrice(price);
}
//get、set方法
public int getId() {
return this.id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
public String getCategories() {
return this.categories;
}
public void setCategories(String categories) {
this.categories = categories;
}
public double getPrice() {
return this.price;
}
public void setPrice(double price) {
this.price = price;
}
//重写toString方法
@Override
public String toString() {
// TODO Auto-generated method stub
String str="产品ID:"+this.getId()+"\n产品名称:"+this.getName()+"\n产品属性:"+this.getCategories()+"\n产品价格:"+this.getPrice()+"元";
return str;
}
}
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 TestOne {
public static void main(String[] args) {
// TODO Auto-generated method stub
Product one=new Product(123,"iPhone","telephone",4888);
Product two=new Product(234,"iPad","computer",5088);
Product three=new Product(345,"macbook","computer",10688);
Product four=new Product(256,"iwatch","watch",4799);
try {
FileOutputStream fos=new FileOutputStream("..\\..\\File\\Product");
ObjectOutputStream oos=new ObjectOutputStream(fos);
FileInputStream fis=new FileInputStream("..\\..\\File\\Product");
ObjectInputStream ois=new ObjectInputStream(fis);
//写入文件
oos.writeObject(one);
oos.writeObject(two);
oos.writeObject(three);
oos.writeObject(four);
fos.flush();
oos.flush();
//读取文件
for(int n=0;n<4;n++) {
Product product=(Product)ois.readObject();
System.out.println(product);
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();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
展开