Partner – Moderne – NPI EA (cat=Spring Boot)
announcement - icon

Refactor Java code safely — and automatically — with OpenRewrite.

Refactoring big codebases by hand is slow, risky, and easy to put off. That’s where OpenRewrite comes in. The open-source framework for large-scale, automated code transformations helps teams modernize safely and consistently.

Each month, the creators and maintainers of OpenRewrite at Moderne run live, hands-on training sessions — one for newcomers and one for experienced users. You’ll see how recipes work, how to apply them across projects, and how to modernize code with confidence.

Join the next session, bring your questions, and learn how to automate the kind of work that usually eats your sprint time.

Course – Black Friday 2026 – NPI EA – main – before_post_content
announcement - icon

Yes, we're now running our Black Friday Sale. All Courses are 33% off until 1st December, 2026 at 17:00 Romania time:

>> EXPLORE ACCESS NOW

Course – Black Friday 2026 – NPI – main – before_post_content
announcement - icon

Yes, we're now running our Black Friday Sale. All Courses are 33% off until 1st December, 2026 at 17:00 Romania time:

>> EXPLORE ACCESS NOW

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.

The code backing this article is available on GitHub. Once you're logged in as a Baeldung Pro Member, start learning and coding on the project.
Partner – Moderne – NPI EA (tag=Refactoring)
announcement - icon

Modern Java teams move fast — but codebases don’t always keep up. Frameworks change, dependencies drift, and tech debt builds until it starts to drag on delivery. OpenRewrite was built to fix that: an open-source refactoring engine that automates repetitive code changes while keeping developer intent intact.

The monthly training series, led by the creators and maintainers of OpenRewrite at Moderne, walks through real-world migrations and modernization patterns. Whether you’re new to recipes or ready to write your own, you’ll learn practical ways to refactor safely and at scale.

If you’ve ever wished refactoring felt as natural — and as fast — as writing code, this is a good place to start.

Course – Black Friday 2026 – NPI EA – main – after_post_content

announcement - icon

Yes, we're now running our Black Friday Sale. All Courses are 33% off until 1st December, 2026 at 17:00 Romania time:

>> EXPLORE ACCESS NOW

Course – Black Friday 2026 – NPI – main – after_post_content

announcement - icon

Yes, we're now running our Black Friday Sale. All Courses are 33% off until 1st December, 2026 at 17:00 Romania time:

>> EXPLORE ACCESS NOW