如何创建的InputStream基于行的观察到的?

问题描述 投票:0回答:1

很抱歉的基本问题......我有一个函数,它与文件的内容的InputStream,并返回一个对象名单,让我们说的人。

输入文件的每一行包含一个人,所以我想通过线来分析它。没有什么困难的,但是......这个时候,我想用反应式编程。

就像是:

public List<Person> parse(final InputStream is) throws IOException {
    return
    //create an observable wich will split the input in many lines, "\n"
            .map(Person::new)
            .collect(toList());
}

我错过了评论一步,那就是:创建一个可观察的是不是字节型为主,但基于线。

java inputstream reactive-programming
1个回答
3
投票

您可以使用stream的方法String linesBufferedReader

返回Stream,可放置线从该BufferedReader读取元件。

用类似这样的代码:

Stream<String> lines = new BufferedReader(new InputStreamReader(is, cs)).lines();

所以,你的代码应该是这样的:

public List<Person> parse(final InputStream is) throws IOException {
    CharSet cs = ... // Use the right charset for your file
    Stream<String> lines = new BufferedReader(new InputStreamReader(is, cs)).lines();
    return  lines
            .map(Person::new)   
            .collect(toList());
}  
© www.soinside.com 2019 - 2024. All rights reserved.