java serializable读取_Java序列化与反序列化(Serializable)

Java序列化与反序列化(Serializable)

特别注意:

1.要序列化的类必须实现Serializable借口

2.在反序列化(读取对象)的时候必须额外捕获EOFException

3.序列化之后的文件是“乱码”

package com.frank.io;

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;

import java.io.Serializable;

/**

* author:pengyan

* date:Jun 15, 2011

* file:ObjectInputOutputStreamTest.java

*/

public class ObjectInputOutputStreamTest {

String path="E:\\planda.p";

public static void main(String[] args) throws Exception {

ObjectInputOutputStreamTest test=new ObjectInputOutputStreamTest();

test.outputObject();

test.inputObject();

}

private void inputObject() throws Exception {

//create inputObjectStream

ObjectInputStream ois=new ObjectInputStream(new FileInputStream(path));

// temp object to receive the value of this stream read everytime

Object obj=null;

PandaEntity p=null;

try {

while((obj=ois.readObject())!=null){

p=(PandaEntity)obj;

//show the object read by the stream

System.out.println(p.toString());

}

} catch (EOFException e) {

//throw EOFException when read end

System.err.println("读取完毕");

}

}

private void outputObject() throws Exception{

//create two object to output

PandaEntity p1=new PandaEntity(1000,"团团",3);

PandaEntity p2=new PandaEntity(2000,"圆圆",3);

//create the output stream

ObjectOutputStream oos=new ObjectOutputStream(new FileOutputStream(path));

//write object

oos.writeObject(p1);

oos.writeObject(p2);

//flush the stream

oos.flush();

//close the stream

oos.close();

}

}

class PandaEntity implements Serializable{

/*the class must implements Serializable interface

* or there will throw java.io.NotSerializableException

* */

private Integer id;

private String name;

private Integer age;

@Override

public String toString() {

return "id:"+id+"\tname:"+name+"\tage:"+age;

}

public PandaEntity() {

}

public PandaEntity(Integer id, String name, Integer age) {

this.id = id;

this.name = name;

this.age = age;

}

public Integer getId() {

return id;

}

public void setId(Integer id) {

this.id = id;

}

public String getName() {

return name;

}

public void setName(String name) {

this.name = name;

}

public Integer getAge() {

return age;

}

public void setAge(Integer age) {

this.age = age;

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值