中文字幕av专区_日韩电影在线播放_精品国产精品久久一区免费式_av在线免费观看网站

溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

JAVA對象和字節數組互轉的方法是什么

發布時間:2020-08-26 09:14:12 來源:億速云 閱讀:977 作者:小新 欄目:編程語言

小編給大家分享一下JAVA對象和字節數組互轉的方法是什么,相信大部分人都還不怎么了解,因此分享這篇文章給大家參考一下,希望大家閱讀完這篇文章后大有收獲,下面讓我們一起去了解一下吧!

【相關學習推薦:java基礎教程】

 創建要轉換的類和主函數

注意這里一定要實現序列化

package day1; 
import java.io.Serializable; 
public class Test360 implements Serializable {
    @Override
    public String toString() {
        return "Test360{" +
            "name='" + name + '\'' +
            '}';
    }
 
    String name="test";
}

對象和字節數組互轉

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 ; i<bufobject.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對象和字節數組互轉的方法是什么的所有內容,感謝各位的閱讀!相信大家都有了一定的了解,希望分享的內容對大家有所幫助,如果還想學習更多知識,歡迎關注億速云行業資訊頻道!

向AI問一下細節

免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI

涿州市| 郴州市| 忻城县| 新巴尔虎左旗| 吉林省| 渝北区| 中山市| 韩城市| 大城县| 麦盖提县| 宁蒗| 石首市| 光泽县| 新民市| 阿合奇县| 宁南县| 广汉市| 舞钢市| 花莲县| 郸城县| 玉屏| 望江县| 西林县| 遵化市| 东方市| 紫云| 红桥区| 永济市| 兴隆县| 宣城市| 五莲县| 夏邑县| 绍兴县| 探索| 同心县| 麦盖提县| 阿瓦提县| 武威市| 荆州市| 建湖县| 台州市|