我一直在努力寻找一种有效的方法来序列化特定类以在我的服务器和客户端之间传递,并且一直在使用ByteOutputArrayStream来传递字节数组。然而,这篇文章让我想知道我是否应该使用 ByteOutputArrayStream。这是我用来序列化和反序列化一个名为的类的编解码器PackagedData
:
public final PackagedData decode(final byte[] data) {
final ByteArrayInputStream bstream = new ByteArrayInputStream(data);
final PackagedData result;
try (final ObjectInputStream ois = new ObjectInputStream(bstream)) {
result = (PackagedData)ois.readObject();
}catch (IOException | ClassNotFoundException e) {
throw new RuntimeException(e.getCause());
}
return result;
}
public final byte[] encode(final PackagedData packagedData) {
final ByteArrayOutputStream bstream = new ByteArrayOutputStream();
try (final ObjectOutputStream oos = new ObjectOutputStream(bstream)) {
oos.writeObject(packagedData);
}
catch (IOException e) {
throw new RuntimeException(e.getCause());
}
return bstream.toByteArray();
}
该类PackagedData
看起来像:
public final class PackagedData implements Serializable {
private final String dataType;
private final String key;
private final Integer value;
public PackagedData(final String dataType, final String key, final Integer value) {
this.dataType = dataType;
this.key = key;
this.value = value;
}
public final String getType(){
return dataType;
}
public final String getKey() {
return key;
}
public final Integer getValue() {
return value;
}
}
我的两个问题是:我应该使用 ByteArrayOutputStream 吗?如果是这样,我应该在参数中将缓冲区大小设置为什么?我了解 ByteArrayOutputStream 会根据需要增加缓冲区大小,但我认为这将比一开始以适当的缓冲区大小初始化它需要更多的资源和时间。
先感谢您。