将InputStream转换为Stream< String>固定长度的字符串 [英] Convert InputStream into Stream<String> of strings of fixed length

查看:135
本文介绍了将InputStream转换为Stream< String>固定长度的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

类似于将InputStream转换为Stream< String>鉴于Charset 我想将 InputStream 转换为 Stream< String>流。但这次不是在新行字符处拆分 InputStream ,而是想将它拆分为相等长度的部分。因此,流的所有字符串都具有相同的长度(在流的最后一个元素上可能有例外,可能更短)。

Like in Convert InputStream into Stream<String> given a Charset I want to convert an InputStream is into a Stream<String> stream. But this time instead of splitting the InputStream at the new line characters, I want to split it into parts of equal length. So all strings of the stream would have the same length (with a possible exception on the last element of the stream, that may be shorter).

推荐答案

没有直接的支持。您可以创建一个直接的工厂方法:

There is no direct support for this. You can create a straight-forward factory method:

static Stream<String> strings(InputStream is, Charset cs, int size) {
    Reader r=new InputStreamReader(is, cs);
    CharBuffer cb=CharBuffer.allocate(size);
    return StreamSupport.stream(new Spliterators.AbstractSpliterator<String>(
        Long.MAX_VALUE, Spliterator.ORDERED|Spliterator.NONNULL) {
            public boolean tryAdvance(Consumer<? super String> action) {
                try { while(cb.hasRemaining() && r.read(cb)>0); }
                catch(IOException ex) { throw new UncheckedIOException(ex); }
                cb.flip();
                if(!cb.hasRemaining()) return false;
                action.accept(cb.toString());
                cb.clear();
                return true;
            }
        }, false).onClose(()->{
            try { r.close(); }catch(IOException ex) { throw new UncheckedIOException(ex); }
        });
}

可以像以下一样使用:

try(Stream<String> chunks=strings(is, StandardCharsets.UTF_8, 100)) {
    // perform operation with chunks
}

这篇关于将InputStream转换为Stream&lt; String&gt;固定长度的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆