[英]Flow publisher to string in java9
如何从Flow.Publisher<Byte> body
获取字符串? 我只想解析来自 Publisher 的字符串。
Flow.Publisher<Byte> bytes = ...;
Flowable.fromPublisher(
FlowAdapters.toPublisher(
bytes
)
).toList()
.map(byteList -> new String(convert(byteList)))
.subscribe((String string) -> {
System.out.println(string);
});
转换定义如下:
static byte[] convert(List<Byte> list) {
final byte[] bytes = new byte[list.size()];
int idx = 0;
for (byte b : list) {
bytes[idx] = b;
idx++;
}
return bytes;
}
通常最好使用已建立的反应库之一,而不是直接使用Flow.Publisher
。
通常,您可以收集字节,并在序列完成时将其转换为字符串:
Flow.Publisher<Byte> bytes = ...
bytes.subscribe(new Flow.Subscriber<Byte>() {
ByteArrayOutputStream bout = new ByteArrayOutputStream();
@Override
public void onSubscribe(Flow.Subscription s) {
s.request(Long.MAX_VALUE);
}
@Override
public void onNext(Byte t) {
bout.write(b);
}
@Override
public void onError(Throwable t) {
t.printStackTrace();
}
@Override
public void onComplete() {
try {
System.out.println(bout.toString("UTF-8"));
} catch (Throwable e) {
e.printStackTrace();
}
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.