首页后端开发其他后端知识JAVA中对象和字节数组互转的过程方法是什么

JAVA中对象和字节数组互转的过程方法是什么

时间2024-03-27 10:20:03发布访客分类其他后端知识浏览384
导读:在这篇文章中,我们将学习“JAVA中对象和字节数组互转的过程方法是什么”的相关知识,下文有详细的介绍及示例,小编觉得挺不错的,有需要的朋友可以借鉴参考,希望对大家阅读完这篇能有所获。 【相关学习推荐:java基础教...
在这篇文章中,我们将学习“JAVA中对象和字节数组互转的过程方法是什么”的相关知识,下文有详细的介绍及示例,小编觉得挺不错的,有需要的朋友可以借鉴参考,希望对大家阅读完这篇能有所获。


 


【相关学习推荐:java基础教程】

0x01 创建要转换的类和主函数

注意这里一定要实现序列化

package day1;
     
import java.io.Serializable;
 
public class Test360 implements Serializable {

    @Override
    public String toString() {

        return "Test360{
" +
            "name='" + name + '\'' +
            '}
    ';

    }
    
 
    String name="test";

}
    

0x02 对象和字节数组互转

package day1;
     
import sun.jvm.hotspot.utilities.Assert;
     
import java.io.*;

 
public class arreytobytes  {

  public static void main(String[] args) throws Exception {
    
    Test360 test =new Test360();
    
    System.out.print ( "java class对象转字节数组\n" );
    
    byte[] bufobject = getBytesFromObject(test);
    
    for(int i=0 ;
     ibufobject.length ;
 i++) {
    
      System.out.print(bufobject[i] + ",");

    }
    
    System.out.println ("\n");
    
    System.out.print ("字节数组还原对象\n");
    
    Object object1 = null;
    
    object1=deserialize(bufobject);
    
    Test360 t1 =(Test360)object1;
    
    System.out.println (t1.name);

  }

  public static byte[] getBytesFromObject(Serializable obj) throws Exception {

    if (obj == null) {
    
      return null;

    }
    
    ByteArrayOutputStream bo = new ByteArrayOutputStream();
    
    ObjectOutputStream oos = new ObjectOutputStream(bo);
    
    oos.writeObject(obj);
    
    return bo.toByteArray();

  }

  public static Object deserialize(byte[] bytes) {
    
    Object object = null;

    try {
    
      ByteArrayInputStream bis = new ByteArrayInputStream(bytes);
    //
      ObjectInputStream ois = new ObjectInputStream(bis);
    
        object = ois.readObject();
    
      ois.close();
    
      bis.close();

    }
 catch (IOException ex) {
    
      ex.printStackTrace();

    }
 catch (ClassNotFoundException ex) {
    
      ex.printStackTrace();

    }
    
    return object;

  }

}

运行结果

java class对象转字节数组

-84,-19,0,5,115,114,0,12,100,97,121,49,46,84,101,115,116,51,54,48,76,-69,81,12,-51,122,126,-123,2,0,0,120,112,

字节数组还原对象

test

补充知识:java对象与byte[]数组之间的相互转化,压缩解压缩操作

下面介绍一下java对象之间和byte[]数组之间的相互转化。并对byte[]数据进行压缩操作。java对象转化为byte[]数组可用于redis中实现缓存。(这里暂不做介绍).话不多说直接开实例:

首先我们创建一个java对象:Person.java

public class Person implements Serializable{
    
  private String userName;
    
  private String password;
    
  private String phone;
    
  private String email;
    
  private String sex;
    
  private String age;


  public Person(){
}


  public Person(String userName, String password, String phone, String email,
      String sex, String age) {
    
    super();
    
    this.userName = userName;
    
    this.password = password;
    
    this.phone = phone;
    
    this.email = email;
    
    this.sex = sex;
    
    this.age = age;

  }

  @Override
  public String toString() {
    
    return "Person [userName=" + userName + ", password=" + password
        + ", phone=" + phone + ", email=" + email + ", sex=" + sex
        + ", age=" + age + "]";

  }

  public String getUserName() {
    
    return userName;

  }

  public void setUserName(String userName) {
    
    this.userName = userName;

  }

  public String getPassword() {
    
    return password;

  }

  public void setPassword(String password) {
    
    this.password = password;

  }

  public String getPhone() {
    
    return phone;

  }

  public void setPhone(String phone) {
    
    this.phone = phone;

  }

  public String getEmail() {
    
    return email;

  }

  public void setEmail(String email) {
    
    this.email = email;

  }

  public String getSex() {
    
    return sex;

  }

  public void setSex(String sex) {
    
    this.sex = sex;

  }

  public String getAge() {
    
    return age;

  }

  public void setAge(String age) {
    
    this.age = age;

  }

}

下面演示对person对象的转换:Object2ByteArray.java

public class Object2ByteArray {

  public static void main(String[] args) {

    try {
    
      Person person=new Person("userName", "password", "phone", "email", "sex", "age");
    
      System.out.println("person:"+person);
    
      ByteArrayOutputStream bos=new ByteArrayOutputStream();
    
      ObjectOutputStream oos=new ObjectOutputStream(bos);
    
      oos.writeObject(person);
    
      //得到person对象的byte数组
      byte[] personByteArray = bos.toByteArray();
    
      System.out.println("before compress:"+personByteArray.length);
    
      //将byte数据压缩
      byte[] zipPersonByteArray = compress(personByteArray);
    
      System.out.println("after compress:"+zipPersonByteArray.length);
    
      closeStream(oos);
    
      closeStream(bos);
    
      //从byte数组中还原person对象
      ByteArrayInputStream bin=new ByteArrayInputStream(personByteArray);
    
      ObjectInputStream ois=new ObjectInputStream(bin);
    
      Person restorePerson = (Person) ois.readObject();
    
      System.out.println(restorePerson);
    
      closeStream(ois);
    
      closeStream(bin);
    
      //从压缩的byte数组中还原person对象
      byte[] unCompressByte = unCompress(zipPersonByteArray);
    
      ByteArrayInputStream zipBin=new ByteArrayInputStream(unCompressByte);
    
      ObjectInputStream zipOis=new ObjectInputStream(zipBin);
    
      Person zipBytePerson=(Person) zipOis.readObject();
    
      System.out.println("compress person:"+zipBytePerson.toString());
    
      closeStream(zipOis);
    
      closeStream(zipBin);

    }
 catch (Exception e) {
    
      e.printStackTrace();

    }


  }


  /**
   *   
   * @description   关闭数据流
   * @param oStream    
   *   
   */
  public static void closeStream(Closeable oStream){

    if(null!=oStream){

      try {
    
        oStream.close();

      }
 catch (IOException e) {
    
        oStream=null;
    //赋值为null,等待垃圾回收
        e.printStackTrace();

      }

    }

  }


  /**
   *   
   * @description   将byte 数组压缩
   * @param bt
   * @return   
   */
  public static byte[] compress(byte[] bt){
    
    //将byte数据读入文件流
    ByteArrayOutputStream bos=null;
    
    GZIPOutputStream gzipos=null;

    try {
    
      bos=new ByteArrayOutputStream();
    
      gzipos=new GZIPOutputStream(bos);
    
      gzipos.write(bt);

    }
 catch (Exception e) {
    
      e.printStackTrace();

    }
finally{
    
      closeStream(gzipos);
    
      closeStream(bos);

    }
    
    return bos.toByteArray();

  }


  /**
   *   
   * @description   解压缩byte数组
   * @param bt
   * @return   
   */
  public static byte[] unCompress(byte[] bt){
    
    //byte[] unCompress=null;
    
    ByteArrayOutputStream byteAos=null;
    
    ByteArrayInputStream byteArrayIn=null;
    
    GZIPInputStream gzipIn=null;

    try {
    
      byteArrayIn=new ByteArrayInputStream(bt);
    
      gzipIn=new GZIPInputStream(byteArrayIn);
    
       byteAos=new ByteArrayOutputStream();
    
      byte[] b=new byte[4096];
    
      int temp = -1;
    
      while((temp=gzipIn.read(b))>
0){
    
        byteAos.write(b, 0, temp);

      }

    }
 catch (Exception e) {
    
      e.printStackTrace();
    
      return null;

    }
finally{
    
      closeStream(byteAos);
    
      closeStream(gzipIn);
    
      closeStream(byteArrayIn);

    }
    
    return byteAos.toByteArray();

  }

}
    

上面的示例显示了:java对象到byte[]数据的转化;

byte[]数据的压缩和解压缩操作;

byte[]数据还原java对象的操作;

运行结果:

person:Person [userName=userName, password=password, phone=phone, email=email, sex=sex, age=age]
before compress:189
after compress:156
Person [userName=userName, password=password, phone=phone, email=email, sex=sex, age=age]
compress person:Person [userName=userName, password=password, phone=phone, email=email, sex=sex, age=age]



通过以上内容的阐述,相信大家对“JAVA中对象和字节数组互转的过程方法是什么”已经有了进一步的了解,更多相关的问题,欢迎关注网络或到官网咨询客服。

声明:本文内容由网友自发贡献,本站不承担相应法律责任。对本内容有异议或投诉,请联系2913721942#qq.com核实处理,我们将尽快回复您,谢谢合作!

JAVA对象

若转载请注明出处: JAVA中对象和字节数组互转的过程方法是什么
本文地址: https://pptw.com/jishu/654155.html
DragonBones的常用术语是什么意思,如何使用 HTML5的details、summary是什么,怎么实现交互效果

游客 回复需填写必要信息