Convert object to byte array in java

First, the object must inherit the Serializable interface

Convert bytes to objects

public static Object ByteToObject(byte[] bytes) {  
Object obj = null;  
try {  
    // bytearray to object  
    ByteArrayInputStream bi = new ByteArrayInputStream(bytes);  
    ObjectInputStream oi = new ObjectInputStream(bi);  
  
    obj = hi.readObject();  
    bi.close();  
    oi.close();  
} catch (Exception e) {  
    System.out.println("translation" + e.getMessage());  
    e.printStackTrace ();  
}  
       return obj;  
   }  

 convert image to bytes

public static byte[] ObjectToByte(java.lang.Object obj) {  
    byte[] bytes = null;  
    try {  
        // object to bytearray  
        ByteArrayOutputStream bo = new ByteArrayOutputStream();  
        ObjectOutputStream oo = new ObjectOutputStream(bo);  
        oo.writeObject(obj);  
  
        bytes = bo.toByteArray();  
  
        bo.close();  
        oo.close();  
    } catch (Exception e) {  
        System.out.println("translation" + e.getMessage());  
        e.printStackTrace ();  
    }  
    return bytes;  

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326383934&siteId=291194637