将发布者流向 java9 中的字符串

Flow publisher to string in java9

如何从 Flow.Publisher<Byte> body 获取字符串? 我只想解析来自 Publisher 的字符串。

通常最好使用已建立的反应库之一而不是 直接与 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();
        }
    }
});

这就是你如何使用 RxJava2:

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;
    }