Search code examples
javainputstreamreactive-programming

How to create a line-based observable from InputStream?


Sorry for the basic question... I have a function that takes an InputStream with the content of a file, and returns a list of objects, let's say Person.

Every line of the input file contains a person, so I want to parse it by line. Nothing difficult but... this time I want to use reactive programming.

Something like:

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

I miss the commented step, that is: creating an observable that is not byte based, but line-based.


Solution

  • You can create a stream of String using the method lines of BufferedReader:

    Returns a Stream, the elements of which are lines read from this BufferedReader.

    with a code similar to this one:

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

    So your code should be something like:

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