java伪装反序列化字节流_JAVA序列化和反序列化 对象<=>IO流 对象<=>字节数组

packagecom.cmy.demo;importjava.io.ByteArrayInputStream;importjava.io.ByteArrayOutputStream;importjava.io.File;importjava.io.FileInputStream;importjava.io.FileNotFoundException;importjava.io.FileOutputStream;importjava.io.IOException;importjava.io.ObjectInputStream;importjava.io.ObjectOutputStream;importcom.cmy.serial.Student;public classUserStudent {/***@paramargs

*@throwsIOException

*@throwsClassNotFoundException*/

public static void main(String[] args) throwsIOException, ClassNotFoundException {

Student st= new Student("Tom",'M',20,3.6);

File file= new File("C:\\YiKiChen\\pacho\\student.txt");try{

file.createNewFile();

}catch(Exception e) {

e.printStackTrace();

}//序列化 对象转换成io流

try{

FileOutputStream fos= newFileOutputStream(file);

ObjectOutputStream oos= newObjectOutputStream(fos);

oos.writeObject(st);

oos.flush();

oos.close();

fos.close();

}catch(Exception e) {

e.printStackTrace();

}//反序列 io转换成对象

try{

FileInputStream fis= newFileInputStream(file);

ObjectInputStream ois= newObjectInputStream(fis);

Student st1=(Student)ois.readObject();

System.out.println(st1.getName());

System.out.println(st1.getGpa());

System.out.println(st1.getSex());

}catch(FileNotFoundException e) {//TODO Auto-generated catch block

e.printStackTrace();

}

}/*** 对象转数组

*@paramobj

*@return

*/

public byte[] toByteArray (Object obj) {byte[] bytes = null;

ByteArrayOutputStream bos= newByteArrayOutputStream();try{

ObjectOutputStream oos= newObjectOutputStream(bos);

oos.writeObject(obj);

oos.flush();

bytes=bos.toByteArray ();

oos.close();

bos.close();

}catch(IOException ex) {

ex.printStackTrace();

}returnbytes;

}/*** 数组转对象

*@parambytes

*@return

*/

public Object toObject (byte[] bytes) {

Object obj= null;try{

ByteArrayInputStream bis= newByteArrayInputStream (bytes);

ObjectInputStream ois= newObjectInputStream (bis);

obj=ois.readObject();

ois.close();

bis.close();

}catch(IOException ex) {

ex.printStackTrace();

}catch(ClassNotFoundException ex) {

ex.printStackTrace();

}returnobj;

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值