Object转换byte[],byte[]转换Object的传统转换以及AMF的实现方式.(1)

package cn.vicky.unit; import java.io.ByteArrayOutputStream; import java.io.DataOutputStream; import java.io.IOException; import java.io.UnsupportedEncodingException; import flex.messaging.io.SerializationContext; import flex.messaging.io.amf.Amf3Output; public class AMF3Test { public static void main(String[] args) { String string = new String("123abc黄维啊啊"); // 数字与英语占1字节,中文占2字节 byte[] b1 = string.getBytes(); System.out.println("普通转换 : " + b1.length); // 14 String s1 = new String(b1); System.out.println(s1); // 123abc黄维啊啊 // for (int i = 0; i < b1.length; i++) { // System.out.println(b1[i]); // } try { byte[] b2 = string.getBytes("UTF-8"); // 数字与英语占1字节,但UTF-8的中文占3字节 System.out.println("UTF-8转换 : " + b2.length); // 18 = 14 + 4(UTF-8的中文) String s2 = new String(b2); System.out.println(b2); // [B@de6ced String s3 = new String(b2, "UTF-8"); // 123abc黄维啊啊 System.out.println(s3); // for (int i = 0; i < b2.length; i++) { // System.out.println(b2[i]); // } } catch (UnsupportedEncodingException e1) { e1.printStackTrace(); } // 将Object转换为byte[] SerializationContext serializationContext = new SerializationContext(); Amf3Output amf3output = new Amf3Output(serializationContext); ByteArrayOutputStream bos = new ByteArrayOutputStream(); DataOutputStream dos = new DataOutputStream(bos); amf3output.setOutputStream(bos); amf3output.reset(); bos.reset(); try { amf3output.writeObject(string); amf3output.flush(); bos.flush(); } catch (IOException e) { e.printStackTrace(); } byte[] objToBytes = bos.toByteArray(); System.out.println("AMF转换 : " + objToBytes.length); // 20 在UTF-8的基础上,在数组头增加了2个字符。 /* 6 37 // 6与37为AMF转换Object为byte[]时候增加的数据,其中37 = 18*2 +1 = 37。其中18为真实数据byte[]的的长度。 49 50 51 97 98 99 -23 -69 -124 -25 -69 -76 -27 -107 -118 -27 -107 -118 */ byte[] newObjToBytes = new byte[objToBytes.length - 2]; System.arraycopy(objToBytes, 2, newObjToBytes, 0, newObjToBytes.length); // for (int i = 0; i < objToBytes.length; i++) { // System.out.println(objToBytes[i]); // } try { String message1 = new String(objToBytes); System.out.println(message1); // %123abc榛勭淮鍟婂晩 String message2 = new String(objToBytes, "UTF-8"); System.out.println(message2); // %123abc黄维啊啊 } catch (UnsupportedEncodingException e) { e.printStackTrace(); } try { String message3 = new String(newObjToBytes); System.out.println(message3); // 123abc榛勭淮鍟婂晩 String message4 = new String(newObjToBytes, "UTF-8"); System.out.println(message4); // 123abc黄维啊啊 } catch (UnsupportedEncodingException e) { e.printStackTrace(); } } }

 

 

打印:

 

普通转换 : 14 123abc黄维啊啊 UTF-8转换 : 18 [B@de6ced 123abc黄维啊啊 AMF转换 : 20 %123abc榛勭淮鍟婂晩 %123abc黄维啊啊 123abc榛勭淮鍟婂晩 123abc黄维啊啊

你可能感兴趣的:(Object转换byte[],byte[]转换Object的传统转换以及AMF的实现方式.(1))