Java – Reader to String

In this quick tutorial we’re going to convert a Reader into a String using plain Java, Guava and the Apache Commons IO library.

This article is part of the “Java – Back to Basic” series here on VietMX’s Blog.

1. With Java

Let’s start with a simple Java solution that reads characters sequentially from the Reader:

@Test
public void givenUsingPlainJava_whenConvertingReaderIntoStringV1_thenCorrect() 
  throws IOException {
    StringReader reader = new StringReader("text");
    int intValueOfChar;
    String targetString = "";
    while ((intValueOfChar = reader.read()) != -1) {
        targetString += (char) intValueOfChar;
    }
    reader.close();
}

If there is a lot of content to read, a bulk-read solution will work better:

@Test
public void givenUsingPlainJava_whenConvertingReaderIntoStringV2_thenCorrect() 
  throws IOException {
    Reader initialReader = new StringReader("text");
    char[] arr = new char[8 * 1024];
    StringBuilder buffer = new StringBuilder();
    int numCharsRead;
    while ((numCharsRead = initialReader.read(arr, 0, arr.length)) != -1) {
        buffer.append(arr, 0, numCharsRead);
    }
    initialReader.close();
    String targetString = buffer.toString();
}

2. With Guava

Guava provides a utility that can do the conversion directly:

@Test
public void givenUsingGuava_whenConvertingReaderIntoString_thenCorrect() 
  throws IOException {
    Reader initialReader = CharSource.wrap("With Google Guava").openStream();
    String targetString = CharStreams.toString(initialReader);
    initialReader.close();
}

3. With Commons IO

Same with Apache Commons IO – there is an IO utility capable of performing the direct conversion:

@Test
public void givenUsingCommonsIO_whenConvertingReaderIntoString_thenCorrect() 
  throws IOException {
    Reader initialReader = new StringReader("With Apache Commons");
    String targetString = IOUtils.toString(initialReader);
    initialReader.close();
}

And there you have it – 4 ways of transforming a Reader into a plain String. Make sure to check out the sample over on GitHub.

Related posts:

Check If a File or Directory Exists in Java
Java 8 Streams peek() API
Recommended Package Structure of a Spring Boot Project
How to Store Duplicate Keys in a Map in Java?
Spring MVC Custom Validation
Using a List of Values in a JdbcTemplate IN Clause
Exploring the Spring 5 WebFlux URL Matching
SOAP Web service: Authentication trong JAX-WS
Java Program to Implement Sorted List
Java Program to Implement Hash Tree
Reactive Flow with MongoDB, Kotlin, and Spring WebFlux
ETL with Spring Cloud Data Flow
Guide to DelayQueue
Java Program to Represent Graph Using 2D Arrays
Java Program to Implement Interpolation Search Algorithm
Login For a Spring Web App – Error Handling and Localization
Notify User of Login From New Device or Location
Hướng dẫn Java Design Pattern – Iterator
Java Program to Use the Bellman-Ford Algorithm to Find the Shortest Path
Chuyển đổi giữa các kiểu dữ liệu trong Java
Guide to Java OutputStream
Java Program to Implement EnumMap API
Assert an Exception is Thrown in JUnit 4 and 5
Java Program to Implement Shell Sort
Java Program to Implement Pollard Rho Algorithm
Giới thiệu Swagger – Công cụ document cho RESTfull APIs
Java Program to Test Using DFS Whether a Directed Graph is Weakly Connected or Not
Java Program to Implement Gaussian Elimination Algorithm
Java Program to Perform Postorder Recursive Traversal of a Given Binary Tree
Java Program to Implement K Way Merge Algorithm
Java Program to Check whether Directed Graph is Connected using DFS
How to Change the Default Port in Spring Boot