码迷,mamicode.com
首页 > 其他好文 > 详细

对象序列化和反序列化

时间:2016-09-06 15:29:35      阅读:165      评论:0      收藏:0      [点我收藏+]

标签:

package com.cn.core.util;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

public class ObjectConvertor {
	/**
	 * 序列化
	 * @param obj
	 * @return
	 */
	public static byte[] serialize(Object obj) {
		if (obj == null) {
			throw new NullPointerException("Can‘t serialize null");
		}
		byte[] object = null;
		ByteArrayOutputStream bos = null;
		ObjectOutputStream os = null;
		try {
			bos = new ByteArrayOutputStream();
			os = new ObjectOutputStream(bos);
			os.writeObject(obj);
			object = bos.toByteArray();
		} catch (IOException e) {
			throw new IllegalArgumentException("Non-serializable object", e);
		} finally {
			try {
				if (os != null)
					os.close();
				if (bos != null)
					bos.close();
			} catch (Exception ex) {
				ex.printStackTrace();
			}
		}
		return object;
	}

	/**
	 * 反序列化
	 * @param in
	 * @return
	 */
	public static Object deserialize(byte[] bt) {
		Object object = null;
		ByteArrayInputStream bis = null;
		ObjectInputStream is = null;
		try {
			if (bt != null) {
				bis = new ByteArrayInputStream(bt);
				is = new ObjectInputStream(bis);
				object = is.readObject();
				is.close();
				bis.close();
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (is != null)
					is.close();
				if (bis != null)
					bis.close();
			} catch (Exception e2) {
				e2.printStackTrace();
			}
		}
		return object;
	}
}

  

对象序列化和反序列化

标签:

原文地址:http://www.cnblogs.com/shell-blog/p/5845631.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!