Java Serializable Object to Byte Array

后端 未结 12 1321
春和景丽
春和景丽 2020-11-22 03:12

Let\'s say I have a serializable class AppMessage.

I would like to transmit it as byte[] over sockets to another machine where it is rebuil

12条回答
  •  臣服心动
    2020-11-22 03:31

    This is just an optimized code form of the accepted answer in case anyone wants to use this in production :

        public static void byteArrayOps() throws IOException, ClassNotFoundException{
    
        String str="123";
         byte[] yourBytes = null;
    
        // Convert to byte[]
    
        try(ByteArrayOutputStream bos = new ByteArrayOutputStream();
                ObjectOutputStream out =  new ObjectOutputStream(bos);) {
    
    
          out.writeObject(str);
          out.flush();
          yourBytes = bos.toByteArray();
    
        } finally {
    
        }
    
        // convert back to Object
    
        try(ByteArrayInputStream bis = new ByteArrayInputStream(yourBytes);
                ObjectInput in = new ObjectInputStream(bis);) {
    
          Object o = in.readObject(); 
    
        } finally {
    
        }
    
    
    
    
    }
    

提交回复
热议问题