码迷,mamicode.com
首页 > 编程语言 > 详细

java对象与字符串的序列化和反序列化

时间:2014-09-23 11:13:34      阅读:611      评论:0      收藏:0      [点我收藏+]

标签:style   blog   color   io   os   java   ar   for   div   

 

package com.mzj.practice.utils;

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

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class SerializeUtils {
    private static final Logger LOG = LoggerFactory.getLogger(SerializeUtils.class);

    /**
     * 对象序列化为字符串
     */
    public static String serialize(Object obj) throws Exception {
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream);
        objectOutputStream.writeObject(obj);
        String serStr = byteArrayOutputStream.toString("UTF-8");
        LOG.info("对象obj:【" + obj + "】序列化serStr:【" + serStr + "】");

        objectOutputStream.close();
        byteArrayOutputStream.close();
        return serStr;
    }

    /**
     * 字符串 反序列化为 对象
     */
    public static Object unSerialize(String serStr) throws Exception {
        ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(serStr.getBytes("UTF-8"));
        ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream);
        Object obj = objectInputStream.readObject();
        LOG.info("对象obj:【" + obj + "】反序列化serStr:【" + serStr + "】");

        objectInputStream.close();
        byteArrayInputStream.close();
        return obj;
    }

}

 

java对象与字符串的序列化和反序列化

标签:style   blog   color   io   os   java   ar   for   div   

原文地址:http://www.cnblogs.com/muzhongjiang/p/3944340.html

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