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

package com.lifeng.seri;

import java.io.ByteArrayInputStream;

import java.io.ByteArrayOutputStream;

import java.io.IOException;

import java.io.ObjectInputStream;

import java.io.ObjectOutput;

import java.io.ObjectOutputStream;

import org.junit.Test;

import com.lifeng.domain.Department;

public class Serial2Obj {

/**

* Object对象与string之间的序列化和反序列化

* @throws IOException

* @throws ClassNotFoundException

*/

@Test

public void obj2String() throws IOException, ClassNotFoundException{

//Object 序列化成string

Department dept = new Department("1","开发部","开发");

ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();

ObjectOutputStream out = new ObjectOutputStream(byteArrayOutputStream);

out.writeObject(dept);

String deptString = byteArrayOutputStream.toString("ISO-8859-1");//必须是ISO-8859-1

System.out.println("===>"+deptString);

//String 的反序列化

ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(deptString.getBytes("ISO-8859-1"));

ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream);

Department dept2 = (Department) objectInputStream.readObject();

System.out.println(dept2);

System.out.println(dept2.getDeptID()+"=="+dept2.getDeptName()+"=="+dept2.getDeptDesc());

out.close();

byteArrayOutputStream.close();

objectInputStream.close();

byteArrayInputStream.close();

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值