java对象序列化实例

package com.lj.serialize;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

public class SerializableTest1
{
public static void main(String[] args) throws IOException, ClassNotFoundException
{
Person p1=new Person(25,"jack",5);
Person p2=new Person(27,"mike",4);
Person p3=new Person(50,"joe",4);

FileOutputStream fos=new FileOutputStream("person.txt");

ObjectOutputStream oos=new ObjectOutputStream(fos);

oos.writeObject(p1);
oos.writeObject(p2);
oos.writeObject(p3);

oos.close();



System.out.println("==============");
FileInputStream fis=new FileInputStream("person.txt");

ObjectInputStream ois=new ObjectInputStream(fis);

Person p=null;
for(int i=0;i<3;i++){
p=(Person) ois.readObject();
System.out.println(p.name+" "+p.age);
}

}
}


class Person implements Serializable{
int age;

String name;

double height;

public Person(int age, String name, double height)
{
this.age = age;
this.name = name;
this.height = height;
}





}



这里我们可以重写serializable接口里面的方法,来具体了解序列化数据的写入和读取的过程:

package com.lj.serialize;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

public class SerializableTest2
{
public static void main(String[] args) throws IOException, ClassNotFoundException
{
Person2 p1=new Person2(25,"jack",5);
Person2 p2=new Person2(27,"mike",4);
Person2 p3=new Person2(50,"joe",4);

FileOutputStream fos=new FileOutputStream("Person2.txt");

ObjectOutputStream oos=new ObjectOutputStream(fos);

oos.writeObject(p1);
oos.writeObject(p2);
oos.writeObject(p3);

oos.close();



System.out.println("==============");
FileInputStream fis=new FileInputStream("Person2.txt");

ObjectInputStream ois=new ObjectInputStream(fis);

Person2 p=null;
for(int i=0;i<3;i++){
p=(Person2) ois.readObject();
System.out.println(p.name+" "+p.age);
}

}
}


class Person2 implements Serializable{
int age;

String name;

double height;

public Person2(int age, String name, double height)
{
this.age = age;
this.name = name;
this.height = height;
}

private void writeObject(ObjectOutputStream out) throws IOException{
out.writeInt(age);
//out.writeChars(name);
out.writeUTF(name);
System.out.println("write object");


}

private void readObject(ObjectInputStream in) throws IOException{
age=in.readInt();
name=in.readUTF();
System.out.println("read object");
}






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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值