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:

Java Program to Implement Meldable Heap
Spring Boot - Unit Test Cases
Java Program to Encode a Message Using Playfair Cipher
Java Program to Solve Travelling Salesman Problem for Unweighted Graph
Exploring the Spring Boot TestRestTemplate
Java Program to Check if a Given Set of Three Points Lie on a Single Line or Not
Java Program to Implement Ternary Heap
Java Program to Implement Double Order Traversal of a Binary Tree
Guide to Guava Multimap
Java Program to Compute the Area of a Triangle Using Determinants
Spring MVC Tutorial
Call Methods at Runtime Using Java Reflection
Custom Cascading in Spring Data MongoDB
Java Program to Implement Graph Structured Stack
Spring’s RequestBody and ResponseBody Annotations
Java Program to Construct an Expression Tree for an Infix Expression
Hướng dẫn sử dụng Lớp FilePermission trong java
Java Program to Describe the Representation of Graph using Incidence Matrix
Converting String to Stream of chars
Java – File to Reader
Java Program to Check Whether a Given Point is in a Given Polygon
Tìm hiểu cơ chế Lazy Evaluation của Stream trong Java 8
Java Program to Implement Skew Heap
Comparing getPath(), getAbsolutePath(), and getCanonicalPath() in Java
Java Program to Perform Complex Number Multiplication
How to Replace Many if Statements in Java
Java Program to Check whether Undirected Graph is Connected using BFS
Logging in Spring Boot
The Modulo Operator in Java
Java Program to Implement D-ary-Heap
Java Program to Implement Knight’s Tour Problem
Predicate trong Java 8