Object转byte[];byte[]转Object

来源:互联网 发布:6s4g网络突然上不了网 编辑:程序博客网 时间:2024/06/06 00:38
对象转数组,数组转对象   

序列化一个对象,反序列化一个对象就是如此  

Java代码
 
package com.digican.utils;     import java.io.ByteArrayInputStream;   import java.io.ByteArrayOutputStream;   import java.io.IOException;   import java.io.ObjectInputStream;   import java.io.ObjectOutputStream;     import com.digican.javabean.TestBean;     public class ObjectAndByte {         /**       * 对象转数组       * @param obj       * @return       */      public byte[] toByteArray (Object obj) {              byte[] bytes = null;              ByteArrayOutputStream bos = new ByteArrayOutputStream();              try {                    ObjectOutputStream oos = new ObjectOutputStream(bos);                     oos.writeObject(obj);                    oos.flush();                     bytes = bos.toByteArray ();                  oos.close();                     bos.close();                } catch (IOException ex) {                    ex.printStackTrace();           }              return bytes;        }              /**       * 数组转对象       * @param bytes       * @return       */      public Object toObject (byte[] bytes) {              Object obj = null;              try {                    ByteArrayInputStream bis = new ByteArrayInputStream (bytes);                    ObjectInputStream ois = new ObjectInputStream (bis);                    obj = ois.readObject();                  ois.close();               bis.close();           } catch (IOException ex) {                    ex.printStackTrace();           } catch (ClassNotFoundException ex) {                    ex.printStackTrace();           }              return obj;        }              public static void main(String[] args) {           TestBean tb = new TestBean();           tb.setName("daqing");           tb.setValue("1234567890");                      ObjectAndByte oa = new ObjectAndByte();           byte[] b = oa.toByteArray(tb);           System.out.println(new String(b));                      System.out.println("=======================================");                      TestBean teb = (TestBean) oa.toObject(b);           System.out.println(teb.getName());           System.out.println(teb.getValue());       }     }  
package com.digican.javabean;
  import java.io.Serializable;     public class TestBean implements Serializable{         private String name;              private String value;         public String getName() {           return name;       }         public void setName(String name) {           this.name = name;       }         public String getValue() {           return value;       }         public void setValue(String value) {           this.value = value;       }          }  
阅读全文
0 0