![](/img/trans.png)
[英]Java Serialization : How use Object InputStream / Object Output Stream
[英]Stream<Object> to InputStream
如何将Stream<Object>
类型转换为InputStream
? 目前,我获取迭代器并遍历所有数据,将其转换为byteArray并将其添加到inputStream:
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(bos);
Iterator<MyType> myItr = MyObject.getStream().iterator();
while (myItr.hasNext()) {
oos.writeObject(myItr.next().toString()
.getBytes(StandardCharsets.UTF_8));
}
oos.flush();
oos.close();
InputStream is = new ByteArrayInputStream(bao.toByteArray());
这样做的开销是多少? 如果我的流包含数TB的数据,我不会将数TB的数据吸入内存吗? 有没有更好的方法来实现这一目标?
您应该能够使用管道将OutputStream
转换为InputStream
:
PipedOutputStream pos = new PipedOutputStream();
InputStream is = new PipedInputStream(pos);
new Thread(() -> {
try (ObjectOutputStream oos = new ObjectOutputStream(pos)) {
Iterator<MyType> myItr = MyObject.getStream().iterator();
while (myItr.hasNext()) {
oos.writeObject(myItr.next().toString()
.getBytes(StandardCharsets.UTF_8));
}
} catch (IOException e) {
// handle closed pipe etc.
}
}).start();
灵感来自这个答案 。
这对你有用吗?
https://gist.github.com/stephenhand/292cdd8bba7a452d83c51c00d9ef113c
它是一个InputStream
实现,它将Stream<byte[]>
作为输入数据。 你只需要.map()
你的abitrary对象到字节数组,但是你希望每个对象都表示为字节。
它只在读取InputStream
时调用Stream
上的终端操作,当消费者读取更多的InputStream
将对象从Stream
拉出,因此它永远不会将整个集合加载到内存中
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.