流类数据转换

本文介绍了一种实现Java对象与字节数组相互转换的方法。具体包括将对象序列化为字节数组的过程,以及如何从字节数组反序列化回原始对象。这些技术在对象在网络上传输或存储时非常有用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

//将对象转为字节数组
 public byte[] object2ByteArray() throws Exception{
  ByteArrayOutputStream baos = new ByteArrayOutputStream();
  DataOutputStream dos = new DataOutputStream(baos);
  
  //通过dos将对象内容写入baos
  dos.writeUTF(this.cname);
  dos.writeUTF(this.phone);
  dos.writeInt(this.age);
  baos.close();
  dos.close();
  
  return baos.toByteArray();//返回字节数组
 }

 //将字节数组转为对象
 public static Customer byteArray2Object(byte[] b) throws Exception{
  ByteArrayInputStream bais = new ByteArrayInputStream(b);
  DataInputStream dis = new DataInputStream(bais);
  //从bais读取内容
  Customer cus = new Customer();
  cus.setCname(dis.readUTF());
  cus.setPhone(dis.readUTF());
  cus.setAge(dis.readInt());
  bais.close();
  dis.close();
  return cus;
 }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值