Giống như những người khác nói ByteBuffer là một bộ đệm của byte vì vậy nếu bạn cần serialize lớp của bạn tốt hơn để thay đổi thành byte [] và sử dụng ByteBuffer trong các lớp đang đọc/ghi dữ liệu vào bean này.
Nhưng nếu bạn cần tuần tự hóa thuộc tính ByteBuffer (ví dụ, sử dụng các đốm màu Cassandra), bạn luôn có thể thực hiện tuần tự hóa tùy chỉnh (kiểm tra url này http://www.oracle.com/technetwork/articles/java/javaserial-1536170.html).
Những điểm chính là:
- dấu ByteBuffer như thoáng (vì vậy nó không đăng theo mặc định)
- thực hiện đọc riêng của bạn/viết cho serialization nơi ByteBuffer -> byte [] khi tuần tự và byte [] -> ByteBuffer trên deserializing.
Hãy thử lớp này và cho tôi biết nếu làm việc này cho bạn:
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;
}
}
Nguồn
2015-11-04 11:00:29
gì lợi thế tôi sẽ mất? Đây là một tệp PDF từ Filechannel.map – jtnire
Nếu bạn đang sử dụng 'ByteBuffer' mà không có lý do cụ thể, thì có lẽ bạn an toàn khi sử dụng mảng byte;) – Bozho