Course – LS – All

Get started with Spring and Spring Boot, through the Learn Spring course:

>> CHECK OUT THE COURSE

1. Introduction

When dealing with input data across different sources in Java, we sometimes encounter situations where we must handle data from an InputStream by converting it into a Stream<String>.

In this tutorial, we’ll look at different approaches to achieve this transformation.

2. Converting With BufferedReader and lines() Method

One effective way to convert an InputStream to a Stream<String> is by using a BufferedReader along with its lines() method.

First, we’ll define a byte array bytes containing a sequence of text lines:

byte[] bytes = "Hello\nWorld\nThis\nis\na\ntest".getBytes(StandardCharsets.UTF_8);
InputStream inputStream = new ByteArrayInputStream(bytes);

In the provided code block, we create a byte array named bytes to hold the UTF-8 encoded representation of the provided text lines. Then, we use the ByteArrayInputStream(bytes) to create an InputStream named inputStream from this byte array.

This setup allows us to simulate an InputStream containing the specified text, which will be used in subsequent examples for conversion into a Stream<String>.

Now, let’s see how we can implement this approach in a test scenario:

@Test
void givenInputStream_whenConvertingWithBufferedReader_thenConvertInputStreamToStringStream() throws IOException {
    try (InputStreamReader isr = new InputStreamReader(inputStream, StandardCharsets.UTF_8);
      BufferedReader reader = new BufferedReader(isr)) {
        Stream<String> stringStream = reader.lines();

        String result = stringStream.reduce("", (s1, s2) -> s1 + s2);

        assertEquals("HelloWorldThisisatest", result);
    }
}

In the example above, we create a BufferedReader object wrapped around the InputStream using an InputStreamReader. This allows us to read lines of text efficiently from the InputStream. Additionally, the lines() method of the BufferedReader returns a Stream<String> containing the lines read from the input. Lastly, we process this Stream to concatenate all the String elements into a single result String using the reduce() operation, which we subsequently validate against the expected content using an assertion.

Note that we utilize try-with-resources to ensure that the InputStreamReader and BufferedReader are automatically closed at the end of the try block, releasing associated resources.

3. Converting with Scanner

Another approach involves using Scanner to tokenize the InputStream. Let’s look at a simple implementation:

@Test
void givenInputStream_whenConvertingWithScannerFindAll_thenConvertInputStreamToStringStream() {
    try (Scanner scanner = new Scanner(inputStream, StandardCharsets.UTF_8)) {
        Stream<String> stringStream = scanner.findAll(".+")
          .map(MatchResult::group);

        String result = stringStream.collect(Collectors.joining());

        assertEquals("HelloWorldThisisatest", result);
    }
}

In this approach, we initialize a Scanner object with the InputStream and configure it to use UTF-8 encoding using StandardCharsets.UTF_8.

Afterward, we employ the findAll() method with the regex pattern “.+” to match one or more characters, effectively capturing the content of the InputStream as a sequence of MatchResult.

Then, we map each match result to its matched group using the MatchResult::group, resulting in a Stream<String> containing the matched strings. Subsequently, we use the Collectors.joining() method to concatenate all the strings in the Stream into a single String named result.

4. Conclusion

In conclusion, converting an InputStream into a Stream<String> in Java is made possible using techniques like BufferedReader with its lines() method or leveraging the Scanner with its findAll() method. This allows for efficient processing of text-based data, providing flexibility and scalability when handling an InputStream in our Java applications.

As always, the source code for the examples is available over on GitHub.

Course – LS – All

Get started with Spring and Spring Boot, through the Learn Spring course:

>> CHECK OUT THE COURSE
res – REST with Spring (eBook) (everywhere)
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments