对象和字节流数组的转换

本文介绍如何将一个简单的Student对象转换为字节流数组,并实现从字节流数组还原回原始对象的过程。该过程利用了Java的字节流输入输出流(如ByteArrayInputStream和ByteArrayOutputStream)以及数据输入输出流(如DataInputStream和DataOutputStream)。通过具体实例演示了整个转换流程。

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

   一个student的对象,将其转为字节流数组以及相反的过程。

 

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;

class Student{//simple class
 private String name;
 private int age;
 public Student(){
  
 }
 public Student(String name, int age) {
  super();
  this.name = name;
  this.age = age;
 }
 public String getName() {
  return name;
 }
 public void setName(String name) {
  this.name = name;
 }
 public int getAge() {
  return age;
 }
 public void setAge(int age) {
  this.age = age;
 }
 
 
}

public class ByteAndObjectText {
 public static Student ByteToObject(byte[] b) throws IOException{
  ByteArrayInputStream bais=new ByteArrayInputStream(b);
  DataInputStream dis=new DataInputStream(bais);
  Student stu=new Student();
  
 // for(int i=0;i<size;i++){
   stu.setName(dis.readUTF());
      stu.setAge(dis.readInt());
  //}
 return stu;
  
  
 }
 public static byte[] ObjectToByte(Student stu) throws IOException{
  ByteArrayOutputStream baos=new ByteArrayOutputStream();
  DataOutputStream dos=new DataOutputStream(baos);
  
  dos.writeUTF(stu.getName());
  dos.writeInt(stu.getAge());
  
  return baos.toByteArray();//转换为字节流。
  
 }
 
 public static void main(String[] agrs) throws IOException{
  Student stu1=new Student("wfj",20);
  Student stu2=ByteAndObjectText.ByteToObject(ByteAndObjectText.ObjectToByte(stu1));
  System.out.println("the stu2 same as stu1: "+stu2.getName()+" "+stu2.getAge());
  
 }

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值