Table of Contents
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:
Using the Map.Entry Java Class
Lập trình đa luồng với CompletableFuture trong Java 8
The DAO with Spring and Hibernate
Using Custom Banners in Spring Boot
JUnit 5 for Kotlin Developers
Display Auto-Configuration Report in Spring Boot
Spring Boot Annotations
Java Program to Implement Hash Tables
REST Web service: Basic Authentication trong Jersey 2.x
The Registration API becomes RESTful
Custom Error Pages with Spring MVC
How to Find an Element in a List with Java
Java – InputStream to Reader
Java Program to Implement Find all Forward Edges in a Graph
Rest Web service: Filter và Interceptor với Jersey 2.x (P1)
Java Program to Check Whether a Given Point is in a Given Polygon
Use Liquibase to Safely Evolve Your Database Schema
Spring Data MongoDB Transactions
An Example of Load Balancing with Zuul and Eureka
Validations for Enum Types
Hướng dẫn Java Design Pattern – Observer
Java Program to Implement Park-Miller Random Number Generation Algorithm
Phương thức forEach() trong java 8
Collect a Java Stream to an Immutable Collection
Spring Security – Reset Your Password
Java Program to Generate Random Numbers Using Probability Distribution Function
Java Program to Perform Right Rotation on a Binary Search Tree
Custom JUnit 4 Test Runners
Multipart Upload with HttpClient 4
Java 9 Stream API Improvements
Lấy ngày giờ hiện tại trong Java
Send an email with an attachment