【相关学习推荐:java基础教程】
0x01 创建要转换的类和主函数
注意这里一定要实现序列化
package day1; import java.io.Serializable; pub = |lic class Test360 implements Serializab; ] = V X y # h hle { @r q v #Override public String toString() { return "Test360{" + r z $ ^ H"name='" + name + '\'' + '}'; } String name="tesd 5 ? K E 2 / x Tt"; }
package dN Z N # ~ I ?ay1; import sun.jvm.[ # ihotspot.utilitie~ h J h I { ! Q Ws.Assert; import java.io.*; public class arr7 w o l I )eytobytes { public static void main(String[] args) throws Exception { Test360 test =new Test360(); System.out.print ( "java class对象转字节e g h数组\n" ); b} ^ V C iyte[] buB _ f [ w f hfobject = getBytesFromObject(test); for(int i=0 ; i<) l ) 4 n P s 1bufobject.length ; i++) { System.out.prq l s cint(buE 9 ` =fobject[i] + ","); } System. g 2out.println ("\n"j Y U m o); System.out.print ("字节数组还原对象\n"); Object object1 = null; ob; + B Y & rject1=deseriali. c ( ( ; 9 ze(bufobject); Test360 tq _ : & ) j T ] (1 =(Test360)oC 6 { ? 4 *bject1; System.out.println (t1.name); } public static bytm * Le[] getBytesFromObject(Serializable obj) throws Exception { if (obj == null) { retu} 0 grn null; } ByteArrayOutputStream bo = new ByteArrayOutputStream(); ObjectOutpuU j atStream oos = new ObjeY & s u X { ^ EctOutputStream(bo)^ Q 4 z d 6 B 3; oos.writeObject(obj); return bo.toByteArray(); }b v F public static Object deserialize(byte[] bytes) { Object object = null; try { ByteArrayInputStreamn a / [ n B . bis = new ByteArrayInputStream(bytes);// ObjectInputStream ois = new Object: + w 2 = X FInputStream(bisK n P C X 6)9 v Z D; object = ois.readObject(); ois.close(); bis.close(); } catch (IOExcepto @ s qiok { n ex) { ex.printStackTrace(); } catch (ClassNop W I U d JtFoundException ex) { ex.printU { StackTrace(); } return object; } }
运行结果
java class对象转字节数组
-84,-19,0,5,115,114,0,12,100,9I / G7,121,49,46,845 / ,101,115,116,51,54,48,76,-69,81,12{ 2 ! 7 &,-51,122,126,-123,2,0,0,120,112,
字节数组还原对象
test
补充知识:java对t K =象与byte[]数组A , I C P E K V之间的相互转化,压缩解压缩操作
下面介绍一下java对象之间和byte[]数组之间的相互转化。并对byte[]数据进行压缩操作。java对象转化为byte[]数组可用于redis中实现缓存。(这里暂不做介绍).$ ^ ] Q . a话不多说直接开实例:
首先我们创建一个java对象:Person.java
public class Person implements Serializable{ private String us/ Z 2erName; private String passB l r M 8word; private String phons ^ , k X se;* + z private String email; private String sex; private String age; public Person(){} public Person(S$ T H z o ztring userName, String password, String phone, StringV [ p V c ) ] 9 email, String sex, String aH $ C N & lge) { super(); this.user% Y K 7 m } 0Name = userName; this.password = pas, } O + g : 8 . ksword; this.phone = phone; this.email = email; this.sex = sex; this.age = ag% j C o M V _ ye; } @Override public String toString() { reY : s u H : ( $turn "Person [userName=" + userName + ", passX K 4 / p vwD 1 yord=" + password +@ U ? ", phone=" + phone + ", emai5 T o J l /l=" + email + ", sc M : +ex=" + sex + ", age=" + age + "]"; } public String getU# y o V -serName() { return userNN g ~ v Wame; }= . 9 ; = 5 w public void setUse9 # f SrName(String userName) { this.userN) D 1 (ame = userName; } public String getPassword() { return password; } public void setPa3 & 6 K U Kssword(String password) { this.password = password; } public String getPhone()P ~ F $ { return phone; } public void se * v c Y ? [ ZtPhone(String phone) { this.phone = phone; } public Strind ) gg getEmail() { re? , ` L U _turn email;R H : W Q 9 2 r } public void setEmail(String email) { thisB 1 ] c.email = email; } public String getSex() { return sex; }N X , B R K @ [ w public void setSex(6 u F Q v R . ) ?String sex) { this.sj p v [ 2 w Mex = sex; } public String getAge() { return age; } public void setAge(String age) { this.age = age; } }
下面演示对peN z X v X R s P irson对象的转换:Object2ByteArray.java
public class Object2Bt 2 J / g e RyteAO G l : * + Jrray { public static void main(String[] args) { try { PersonS M 8 person=new Person("userName# l p u", "password", "phone", "email",t 9 a i 9 Q o @ "sex", "age"); System.out.println("person:"+person); ByteArrayOutputStream bos=new ByteArrayOutputStr- C * g j e 5eam(); ObjectOutputStream oI - Ros=new ObjectOutputStream(bos); o8 m z 7 6 6os.writeObject(person); //得到person对象的byte数组 byte[] personByteArray = bos.toByteArray(); System.out.priK V 4ntln("befL s 2 : R Z 8 ~ore compress:g @ 3 -"+personByteArray.length); //将byte数据压缩 byte[] zipPersonByteArray = compress(persT = z ] 1 qonByteArray); System.out.println("after compr: % g eess:"+zipPersonByteArrar | 8 Q jy.lengQ ( n y 6 ? Mth); closeStream(oos); cloo ; 9seStream(bos); //从byte数组中还原p$ z ]erson对象 ByteArrayInputStream bin=new ByteArrayInputStream(personBytex Q u t :Arran ^ g N 0 @ vy); ObjectInputStream ois=new ObjectInputStream(bin); Person resI s 8 = 5 ptoX u s qrePerson = (Person) ois.readObject(); System.out.println(restorePerson); closeStream(ois); closeStream(bin); //从压缩V R Q = @ &的byte数组中还原person对象 byte[] unCompressByte = unCompress(zipPersonByteArrayr n G 9 N W K); ByteArrayInpI / H T b % K p rutStream zipBin=new ByteArrayInputStream(unCompressByte); ObjectInputStream zipOis=new ObjectInputStream(zipBin); Person zipBytePerson=(Person) zipOis.readObject(); System.out.println("compress person:"+zipBytePerson.toString()); closeStream(zipOis); clos+ t : K J 4 ^eStre i | . eam(zipBin); } catch (Exception e) { e.printStackTrace(); } } /** * * @description 关闭数据流 * @param oStream * */ py N z ~ 9 ) g &ublic static void closeStream(Closeable oStream){ if(null!=oStream){ try { oStream.close(); } catch (IOException e) { oStream=null;//赋值为null,等待垃圾回收 e., m P JprintStackTrace();b 9 M z _ ; } } } /** * * @description 将byte 数组压缩 * @param bE P ? ft * @return */ public s7 3 C c s g G _tatic byte* i 8 { Z e G l[] compress(byt. ! J | o k & Me[] bt){ //将byte数Y 5 w @ t据读入文件流 ByteArrayOutputStream bos=null; GZIPOutputStream gzipos=nh R i 6 sull; try { bos=new ByteArrayOutputStream(); gzipos=newv I ( [ GZIPOutputStream(bos); gzipos.write(bt); } catch (Exceptiol i 2 Qn e) { e.printStackTrace(); }finally{ closeStream(gzipos); closeStream(bos); } return bos.toByteArray(); } /** * * @description 解压缩byte数组 * @param btj [ L * @retR % / u ( 8 [ ,urn */ public static byte[] unCompress(byte[] bt){ //byte[] unCompress=null; ByteArrayOutputStrZ W % O Qeam byteAos=null; ByteArrayInputStream byteArrayIn=null;O u # 2 h b W _ 1 GZIPInF 0 q q GputStream gzipIn=null; try { byteArrayIn=new ByteArrayInputStream(bt); gz9 7 l U e T C T JipIn=new G; [ @ 7ZIPInputStream(b) 6 X X | % : xyteArrayIn); byteAos=new ByteArrayOutputStream(); byte[] b=new bytr 5 y M &e[4096]; i+ j = M [nt temp = -1; while((temp=gzipIn.read(b))>0){ byteAos.write(b, 0, temp); } } catch (Exception e) { e.printStackTrace(); return null& i g X C; }finally{ closeStream(byteAos); c- s ? O p closeStream(gzipIn); closeStream(byteArrayIn); } return byteAos.toByte? { K Z 4 s T @Array(); } }
上面的示例显示了:java对象到byte[]数据的转化;
byte[]数据的压缩和解压缩操作;
byte[]数据还原java对象的操作;
运行结果:
person:Person [userName=userName, password=password, phone=phone, email=email, sex=sex, a+ q S # ^ v + y -ge=age] b, f p K G n ) g cefore compress:189 after compress:156 Person [userName=S 6 [ R yuserName, password=password, phone=ph{ N i bone, em| . @ kail=email, sex=sex, a^ i ^ge=age] compress person:. t T k a ~ lPerson [userName=userName, password=password, phone=phone, email=email, sex=sex, age=O 3 V Gaa L # c ng= ? x ) ( h 2 i Fe]
以上就是JAVA对象和字节数组互转过程e K 1 @ 4 & # Z d的详细内容。