java反序列化多个对象_java 为什么序列化多个对象在一个文件里,却反序列化可以读取多个对象...

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();

}

}

}

展开

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值