Matriz de Objetos a Bytes Serializable en Java


Digamos que tengo una clase serializable AppMessage.

Me gustaría transmitirlo como byte[] a través de sockets a otra máquina donde se reconstruye a partir de los bytes recibidos.

¿Cómo podría lograr esto?

Author: lambda, 2010-05-14

6 answers

Prepare bytes para enviar:

ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutput out = null;
try {
  out = new ObjectOutputStream(bos);   
  out.writeObject(yourObject);
  out.flush();
  byte[] yourBytes = bos.toByteArray();
  ...
} finally {
  try {
    bos.close();
  } catch (IOException ex) {
    // ignore close exception
  }
}

Crear objeto a partir de bytes:

ByteArrayInputStream bis = new ByteArrayInputStream(yourBytes);
ObjectInput in = null;
try {
  in = new ObjectInputStream(bis);
  Object o = in.readObject(); 
  ...
} finally {
  try {
    if (in != null) {
      in.close();
    }
  } catch (IOException ex) {
    // ignore close exception
  }
}
 362
Author: Taylor Leese,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-09-18 03:23:24

La mejor manera de hacerlo es usar SerializationUtils desde Apache Commons Lang.

Para serializar:

byte[] data = SerializationUtils.serialize(yourObject);

Para deserializar:

YourObject yourObject = SerializationUtils.deserialize(data)

Como se mencionó, esto requiere la biblioteca Lang de Commons. Se puede importar usando Gradle:

compile 'org.apache.commons:commons-lang3:3.5'

Maven:

<!-- https://mvnrepository.com/artifact/org.apache.commons/commons-lang3 -->
<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-lang3</artifactId>
    <version>3.5</version>
</dependency>

Jar file

Y más formas mencionadas aquí

Alternativamente, se puede importar toda la colección. Consulte este enlace

 262
Author: uris,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-11-09 14:22:50

Si usa Java > = 7, podría mejorar la solución aceptada usando try with resources :

private byte[] convertToBytes(Object object) throws IOException {
    try (ByteArrayOutputStream bos = new ByteArrayOutputStream();
         ObjectOutput out = new ObjectOutputStream(bos)) {
        out.writeObject(object);
        return bos.toByteArray();
    } 
}

Y al revés:

private Object convertFromBytes(byte[] bytes) throws IOException, ClassNotFoundException {
    try (ByteArrayInputStream bis = new ByteArrayInputStream(bytes);
         ObjectInput in = new ObjectInputStream(bis)) {
        return in.readObject();
    } 
}
 67
Author: Víctor Romero,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-08-06 17:36:52

Se puede hacer por SerializationUtils, por serialize & deserialize método por ApacheUtils para convertir objeto a byte [] y viceversa, como se indica en la respuesta @ uris.

Para convertir un objeto a byte [] mediante serialización:

byte[] data = SerializationUtils.serialize(object);

Para convertir byte [] a objeto deserializando::

Object object = (Object) SerializationUtils.deserialize(byte[] data)

Haga clic en el enlace para Descargar org-apache-commons-lang.jar

Integrar .archivo jar haciendo clic en:

Nombre de archivo -> Abrir la Médula Configuración -> Seleccione el módulo de -> las Dependencias -> Agregar archivo Jar y listo.

Espero que esto ayude.

 3
Author: Pankaj Lilan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-04-22 05:01:13

También recomiendo usar la herramienta SerializationUtils. Quiero hacer un ajuste en un comentario equivocado de @Abilash. El método SerializationUtils.serialize() es no restringido a 1024 bytes, contrariamente a otra respuesta aquí.

public static byte[] serialize(Object object) {
    if (object == null) {
        return null;
    }
    ByteArrayOutputStream baos = new ByteArrayOutputStream(1024);
    try {
        ObjectOutputStream oos = new ObjectOutputStream(baos);
        oos.writeObject(object);
        oos.flush();
    }
    catch (IOException ex) {
        throw new IllegalArgumentException("Failed to serialize object of type: " + object.getClass(), ex);
    }
    return baos.toByteArray();
}

A primera vista, usted puede pensar que new ByteArrayOutputStream(1024) solo permitirá un tamaño fijo. Pero si echas un vistazo de cerca a ByteArrayOutputStream, descubrirás que la corriente crecerá si es necesario:

Esta clase implementa un flujo de salida en el que los datos son escrito en un matriz de bytes. El búfer crece automáticamente como datos está escrito en él. Los datos se pueden recuperar utilizando toByteArray() y toString().

 0
Author: gzg_55,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-05-15 07:17:27

Me gustaría transmitirlo como byte[] sobre sockets a otra máquina

// When you connect
ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
// When you want to send it
oos.writeObject(appMessage);

Donde se reconstruye a partir de los bytes recibidos.

// When you connect
ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
// When you want to receive it
AppMessage appMessage = (AppMessage)ois.readObject();
 0
Author: user207421,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-05-15 07:20:06