Search code examples
javamethodsinputstreamsupplier

How can I read a character from an InputStream and return it in a Supplier<Integer> (Java)


So I have a method I need to implement. It gets an InputStream and returns a Supplier like this:

public Supplier<Integer> buildPipe(InputStream input)

Now I want to read a character from the InputStream (probably with the read()-method) and return it, but I have no idea how to store it as an int so I can return it with the Supplier.

I hope someone can help me out.


Solution

  • It is not really possible to go directly from an InputStream to a codepoint without going through a decoding bridge. For that you need to know that Charset, or assume it. InputStreamReader is that bridge.

    for example:

    InputStream is = new ByteArrayInputStream(new byte[]{1,2});
    InputStreamReader reader = new InputStreamReader(is, StandardCharsets.UTF_8);
    

    Now you can have your Supplier from a Reader rather than an input stream.

    Supplier<Integer> next(InputStreamReader reader) {
        Supplier<Integer> s = () -> {
            try {
                return reader.read();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        };
        return s;
    }
    

    Please note that InputStreamReader is stateful and hence your Supplier wont be referential transparent as one would expect.