[英]Using OutputStream with multiple ObjectOutputStreams?
為了從特定的序列化格式中抽象出來,我想定義以下內容:
public interface TransportCodec {
void write(OutputStream out, Object obj) throws IOException;
Object read(InputStream in) throws IOException;
}
默認實現僅使用Java對象序列化,如下所示:
public void write(OutputStream out, Object obj) throws IOException {
ObjectOutputStream oout = new ObjectOutputStream(out);
oout.writeObject(obj);
oout.flush();
}
顯然缺少了oout.close()
,但是有一個原因:我希望能夠通過獨立的write
調用將多個對象寫入同一流。 查看ObjectOutputStream
(jdk 1.8)的源代碼, oout.close()
關閉基礎流,但同時清除ObjectOutputStream
組成部分的數據結構。 但是由於我將oout
留給了垃圾收集器,所以我不會因為不關閉流而出現問題。
除了將來的JDK確實需要oout.close()
的風險外,還有兩個問題:
ObjectOutputStream
時,我在當前JDK中失去什么? ByteArrayOutputStream
,然后將字節復制到out
將允許關閉oout
。 有更好的選擇嗎? 分成兩個接口,並使實現類“擁有”基礎流。
好處:
基礎存儲不再限於OutputStream
/ InputStream
。
通過使兩個接口擴展為Closeable
,它們現在可以在try-with-resources塊中使用。
調用方只需要攜帶一個引用(例如, TransportEncoder
),就不再需要攜帶流(例如, OutputStream
)。
public interface TransportEncoder extends Closeable {
void write(Object obj) throws IOException;
}
public interface TransportDecoder extends Closeable {
Object read() throws IOException;
}
public final class ObjectStreamEncoder implements TransportEncoder {
private final ObjectOutputStream stream;
public ObjectStreamEncoder(OutputStream out) throws IOException {
this.stream = new ObjectOutputStream(out);
}
@Override
public void write(Object obj) throws IOException {
this.stream.writeObject(obj);
}
@Override
public void close() throws IOException {
this.stream.close();
}
}
public final class ObjectStreamDecoder implements TransportDecoder {
private final ObjectInputStream stream;
public ObjectStreamDecoder(InputStream in) throws IOException {
this.stream = new ObjectInputStream(in);
}
@Override
public Object read() throws IOException {
try {
return this.stream.readObject();
} catch (ClassNotFoundException e) {
throw new NoClassDefFoundError(e.getMessage());
}
}
@Override
public void close() throws IOException {
this.stream.close();
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.