Core Java

Processing StringBuilder Line by Line in Java

In Java, a StringBuilder is often used to efficiently build strings through dynamic modifications. However, there are times when you may need to process its contents line by line, similar to how you would read from a file. Let us delve into understanding how to use Java StringBuilder and read line by line for processing text efficiently.

1. Introduction

In Java, a StringBuilder is commonly used for creating and modifying strings dynamically because it is more efficient than using immutable String objects, especially in cases where a lot of concatenation or modifications are required. However, StringBuilder does not provide built-in methods to read its contents line by line. There are several scenarios where you may want to read a StringBuilder line by line, such as parsing multi-line logs, handling formatted input, or simulating file reading from memory. To achieve this, we need to rely on different techniques that convert or process the StringBuilder contents in a way that allows sequential line access.

  • Splitting by line separator – A simple and direct method by breaking the string into an array of lines.
  • Using Scanner – Leverages Java’s Scanner class to iterate line by line in a structured way.
  • Using BufferedReader – Wraps a StringReader with BufferedReader for efficient reading, similar to how files are read.
  • Using Stream API – Utilizes Java 8+ Stream operations to process lines functionally.
  • Manual iteration – Provides full control by iterating character by character and building lines manually.

By understanding and applying these techniques, you can choose the most suitable method depending on whether your use case prioritizes simplicity, efficiency, or flexibility.

2. Code Example

This example demonstrates multiple ways to read the contents of a StringBuilder line by line in one single program.

import java.util.*;
import java.util.stream.*;

public class StringBuilderReaderDemo {

    public static void main(String[] args) throws Exception {
        StringBuilder sb = new StringBuilder();
        sb.append("Line 1\n");
        sb.append("Line 2\n");
        sb.append("Line 3");

        System.out.println("=== Using Split ===");
        readUsingSplit(sb);

        System.out.println("\n=== Using Scanner ===");
        readUsingScanner(sb);

        System.out.println("\n=== Using BufferedReader ===");
        readUsingBufferedReader(sb);

        System.out.println("\n=== Using Stream API ===");
        readUsingStream(sb);

        System.out.println("\n=== Using Manual Iteration ===");
        readUsingManualIteration(sb);
    }

    // 1. Split by line separator
    static void readUsingSplit(StringBuilder sb) {
        String[] lines = sb.toString().split("\\n");
        for (String line : lines) {
            System.out.println(line);
        }
    }

    // 2. Scanner
    static void readUsingScanner(StringBuilder sb) {
        Scanner scanner = new Scanner(sb.toString());
        while (scanner.hasNextLine()) {
            System.out.println(scanner.nextLine());
        }
        scanner.close();
    }

    // 3. BufferedReader
    static void readUsingBufferedReader(StringBuilder sb) throws IOException {
        BufferedReader reader = new BufferedReader(new StringReader(sb.toString()));
        String line;
        while ((line = reader.readLine()) != null) {
            System.out.println(line);
        }
        reader.close();
    }

    // 4. Stream API
    static void readUsingStream(StringBuilder sb) {
        Arrays.stream(sb.toString().split("\\n"))
              .forEach(System.out::println);
    }

    // 5. Manual Iteration
    static void readUsingManualIteration(StringBuilder sb) {
        StringBuilder line = new StringBuilder();
        for (int i = 0; i < sb.length(); i++) {
            char c = sb.charAt(i);
            if (c == '\n') {
                System.out.println(line.toString());
                line.setLength(0);
            } else {
                line.append(c);
            }
        }
        if (line.length() > 0) {
            System.out.println(line.toString());
        }
    }
}

2.1 Code Explanation

This program defines a single StringBuilder containing multiple lines and demonstrates five different methods for reading it line by line: using the split method, the Scanner class, the BufferedReader with a StringReader, the Stream API, and manual character iteration. Each approach prints every line to the console, showing how you can handle StringBuilder content flexibly depending on your requirements, while the main method sequentially calls all five reading methods so that you can see their outputs in one run.

2.2 Code Output

When executed, the program produces the following output:

=== Using Split ===
Line 1
Line 2
Line 3

=== Using Scanner ===
Line 1
Line 2
Line 3

=== Using BufferedReader ===
Line 1
Line 2
Line 3

=== Using Stream API ===
Line 1
Line 2
Line 3

=== Using Manual Iteration ===
Line 1
Line 2
Line 3

Sign up

Yatin Batra

An experience full-stack engineer well versed with Core Java, Spring/Springboot, MVC, Security, AOP, Frontend (Angular & React), and cloud technologies (such as AWS, GCP, Jenkins, Docker, K8).
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button