Object转byte[]←→byte[]转Object

来源:互联网 发布:centos iscsi 编辑:程序博客网 时间:2024/05/28 06:08
  1. import java.io.ByteArrayInputStream;  
  2. import java.io.ByteArrayOutputStream;  
  3. import java.io.IOException;  
  4. import java.io.ObjectInputStream;  
  5. import java.io.ObjectOutputStream;  
  6.   
  7. public class ObjectAndByte {  
  8.   
  9.     /** 
  10.      * 对象转数组 
  11.      * @param obj 
  12.      * @return 
  13.      */  
  14.     public byte[] toByteArray (Object obj) {     
  15.         byte[] bytes = null;     
  16.         ByteArrayOutputStream bos = new ByteArrayOutputStream();     
  17.         try {       
  18.             ObjectOutputStream oos = new ObjectOutputStream(bos);        
  19.             oos.writeObject(obj);       
  20.             oos.flush();        
  21.             bytes = bos.toByteArray ();     
  22.             oos.close();        
  23.             bos.close();       
  24.         } catch (IOException ex) {       
  25.             ex.printStackTrace();  
  26.         }     
  27.         return bytes;   
  28.     }  
  29.       
  30.     /** 
  31.      * 数组转对象 
  32.      * @param bytes 
  33.      * @return 
  34.      */  
  35.     public Object toObject (byte[] bytes) {     
  36.         Object obj = null;     
  37.         try {       
  38.             ByteArrayInputStream bis = new ByteArrayInputStream (bytes);       
  39.             ObjectInputStream ois = new ObjectInputStream (bis);       
  40.             obj = ois.readObject();     
  41.             ois.close();  
  42.             bis.close();  
  43.         } catch (IOException ex) {       
  44.             ex.printStackTrace();  
  45.         } catch (ClassNotFoundException ex) {       
  46.             ex.printStackTrace();  
  47.         }     
  48.         return obj;   
  49.     }  
  50. }  
阅读全文
0 0
原创粉丝点击