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:
Làm thế nào tạo instance của một class mà không gọi từ khóa new?
Spring @Primary Annotation
Mockito and JUnit 5 – Using ExtendWith
Java Program to Use rand and srand Functions
Java Program to Implement Find all Cross Edges in a Graph
Introduction to Spliterator in Java
Java Program to Find a Good Feedback Edge Set in a Graph
A Guide to Java SynchronousQueue
String Processing with Apache Commons Lang 3
Hướng dẫn Java Design Pattern – Bridge
Java 8 Stream API Analogies in Kotlin
Beans and Dependency Injection
Spring Data – CrudRepository save() Method
Java Program to Implement String Matching Using Vectors
Comparing getPath(), getAbsolutePath(), and getCanonicalPath() in Java
Java Map With Case-Insensitive Keys
Java Program to Represent Graph Using 2D Arrays
Java Program to Check Whether a Given Point is in a Given Polygon
Get and Post Lists of Objects with RestTemplate
Java Program to Generate All Possible Subsets with Exactly k Elements in Each Subset
Java – InputStream to Reader
Spring Boot - Tomcat Deployment
Serialize Only Fields that meet a Custom Criteria with Jackson
Lấy ngày giờ hiện tại trong Java
Java Program to Find the Vertex Connectivity of a Graph
Hướng dẫn Java Design Pattern – Memento
Fixing 401s with CORS Preflights and Spring Security
Java Program to Represent Graph Using Adjacency List
Introduction to Java Serialization
Spring MVC and the @ModelAttribute Annotation
Introduction to Project Reactor Bus
Create a Custom Exception in Java