> Java > java지도 시간 > 본문

JAVA 객체와 바이트 배열 상호 변환 과정

coldplay.xixi
풀어 주다: 2020-08-25 16:38:03
앞으로
2804명이 탐색했습니다.

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 객체와 바이트 배열을 각각 변환합니다. other

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 클래스 객체를 바이트 배열로

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

바이트 배열 복원 개체

test

보충 지식: Java 개체와 바이트[] 배열 간의 상호 작용 변환, 압축 및 압축 해제 작업

다음은 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;
  }
}
로그인 후 복사

다음은 사람 개체의 변환을 보여줍니다. 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[] 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 객체와 바이트 배열 상호 변환 과정의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

관련 라벨:
원천:jb51.net
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!