Come altri ha detto ByteBuffer è un involucro di un buffer di byte quindi se avete bisogno di serializzare la classe è meglio cambiare a byte [] e utilizzare ByteBuffer nelle classi che stanno leggendo/scrittura dei dati in questo fagiolo.
Tuttavia, se è necessario serializzare una proprietà ByteBuffer (ad esempio, utilizzare un BLOB Cassandra) è sempre possibile implementare una serializzazione personalizzata (controllare questo URL http://www.oracle.com/technetwork/articles/java/javaserial-1536170.html).
I punti principali sono:
- marchio ByteBuffer come transitoria (quindi non è serializzati per impostazione predefinita)
- implementare la propria lettura/scrittura per la serializzazione in cui ByteBuffer -> byte [] durante la serializzazione e di byte [] -> ByteBuffer sulla deserializzazione.
Prova questa classe e fatemi sapere se questo funziona per voi:
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;
}
}
fonte
2015-11-04 11:00:29
Quali vantaggi starei perdendo? Si tratta di un file PDF da Filechannel.map – jtnire
Se si utilizza 'ByteBuffer' senza un motivo specifico, forse si è sicuri di utilizzare l'array di byte;) – Bozho