Al igual que otros, ByteBuffer es una envoltura de un búfer de bytes por lo que si necesita serializar su clase es mejor cambiar a byte [] y usar ByteBuffer en las clases que leen/escriben datos en este bean.
Pero si necesita serializar una propiedad ByteBuffer (por ejemplo, use las etiquetas de Cassandra) siempre puede implementar una serialización personalizada (consulte esta url http://www.oracle.com/technetwork/articles/java/javaserial-1536170.html).
Los puntos principales son:
- marca ByteBuffer como transitorio (por lo que no es serializados por defecto)
- implementar su propia lectura/escritura para la serialización, donde ByteBuffer -> byte [] cuando la serialización y el byte [] -> ByteBuffer en la deserialización.
Prueba esta clase y quiero saber si esto funciona para usted:
public class NetByteBuffer implements java.io.Serializable {
private static final long serialVersionUID = -2831273345165209113L;
//serializable property
String anotherProperty;
// mark as transient so this is not serialized by default
transient ByteBuffer data;
public NetByteBuffer(String anotherProperty, ByteBuffer data) {
this.data = data;
this.anotherProperty = anotherProperty;
}
public ByteBuffer getData() {
return this.data;
}
private void writeObject(ObjectOutputStream out) throws IOException {
// write default properties
out.defaultWriteObject();
// write buffer capacity and data
out.writeInt(data.capacity());
out.write(data.array());
}
private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
//read default properties
in.defaultReadObject();
//read buffer data and wrap with ByteBuffer
int bufferSize = in.readInt();
byte[] buffer = new byte[bufferSize];
in.read(buffer, 0, bufferSize);
this.data = ByteBuffer.wrap(buffer, 0, bufferSize);
}
public String getAnotherProperty() {
return anotherProperty;
}
}
¿Qué ventajas me gustaría estar perdiendo? Esto es para un archivo PDF de Filechannel.map – jtnire
Si está utilizando 'ByteBuffer' sin una razón específica, entonces quizás esté seguro usando la matriz de bytes;) – Bozho