java序列化

本文详细介绍了Java中对象序列化和反序列化的原理、用途及操作流程,包括序列化的持久化应用、RMI远程方法调用,以及序列化存贮和对象远程调用的具体实现。

序列化:Java中可以把java对象转换成字节序列。

反序列化:把字节序列转换成java对象。

一、序列化的用途

1、java对象序列化的持久化,对象通过序列化后持久化保存到硬盘中,当需要用到该对象时,再从硬盘中取出对象使用,通常是为了保存对象的属性的数据值。例如系统登录用户的session对象,由于登录用户过多,不能全部把用户session全部放到内存,可以把用户session序列化保存到硬盘,需要使用时再从硬盘取回。

2、RMI 远程方法调用,java程序在远程相互调用里,即两个不同的进程之间调用对方的对象,两个进程传输数据是通过二进制序列传输的,需要用到对象的序列化功能。

三、数据序列化存贮

model类:

public class SerializableContainer implements Serializable{

	private static final long serialVersionUID = 6589196133289807424L;

	private String id;
	
	private String name;
	
	private String version;
	
	private Date time;
	
	public SerializableContainer(){}
	
	public SerializableContainer(String id, String name, String version, Date time){
		this.id = id;
		this.name = name;
		this.version = version;
		this.time = time;
	}

	//get,set method of attributes ...
}
测试程序:

public class SerializableLocal {
	
	public static void main(String[] args){
		
		String fileName = "C:/temp/serialiable/SerializableContainer.obj";
		
		serialize(fileName);
		
		deserialize(fileName);
	}
	
	public static String serialize(String fileName){
		SerializableContainer container = new SerializableContainer("ninth", "LAM", "0.01", new Date(System.currentTimeMillis()));

		FileOutputStream fileOutput = null;
		ObjectOutputStream objectOutput = null;
		try {
			File file = new File(fileName);
			if(!file.exists()) file.createNewFile();
			
			fileOutput = new FileOutputStream(file);
			objectOutput = new ObjectOutputStream(fileOutput);
			
			objectOutput.writeObject(container);
			objectOutput.flush();
			
		} catch (IOException e) {
			e.printStackTrace();
		} finally{
			try {
				if(objectOutput != null) objectOutput.close();
				if(fileOutput != null) fileOutput.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return fileName;
	}
	
	public static void deserialize(String fileName){
		FileInputStream fileInput = null;
		ObjectInputStream objectInput = null;
		try {
			fileInput = new FileInputStream(fileName);
			objectInput = new ObjectInputStream(fileInput);
			
			SerializableContainer container = (SerializableContainer) objectInput.readObject();
			System.out.println("id:" + container.getId() + "\n" +
					"name:" + container.getName() + "\n" +
					"version:" + container.getVersion() + "\n" + 
					"time:" + container.getTime());
			
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} finally{
			try {
				if(objectInput != null) objectInput.close();
				if(fileInput != null) fileInput.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

}

四、对象远程调用

详情查看 RMI 远程方法调用

...

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值