1. Introduction
In this article, we will learn how to convert Reader to String using plain Java, Guava
, and Apache Commons IO
library. There is no other solution than reading the content from the Reader
and write it down to the resulted String
, but let's see several different approaches that achieve that.
Check some other useful articles about Java I/O:
2. Convert Reader to String using plain Java
In plain Java, we can use Reader.read(...)
method to read characters sequentially, in a bulk or line by line.
2.1. Using bulk-read
solution
Let's see the solution in which we are reading characters from the Reader
in packages, and appending them into the resulting String:
In this example, the loop goes until all characters are read from the Reader
. StringBuilder
is used to concatenate previously read characters with the new ones.
2.2. Reading line by line using BufferedReader
The BufferedReader
gives us the ability to read characters from the Reader
line by line:
In this example, we are reading line by line from the Reader
in a loop until read String
is null. StringBuilder
is used here to aggregate read lines.
2.3. Reading characters sequentially from the Reader
Let's now take a look at a solution that read characters from the Reader
sequentially:
This approach is probably the least effective. In this example, we read character by character and write it in StringBuilder
.
3. Reader to String using Guava
library
In Guava
we have a special utility class that can do the conversion directly:
In this example we used CharStreams.toString(reader)
method that takes Reader
as a parameter and returns the String
.
4. Reader to String conversion using IOUtils
class from Apache Commons IO
library
The Apache Commons IO
library just like the Guava
gives the direct solution:
In this example we used IOUtils.toString(reader)
method that reads given Reader
and produces the String
.
5. Conclusion
In this article, we presented various ways to convert Reader to a String in Java using built-in methods and external libraries like Guava
and Apache Commons IO
that proved to be more beneficial by providing one-line solutions.
As usual code snippets used in this article are available under our GitHub repository.
{{ 'Comments (%count%)' | trans {count:count} }}
{{ 'Comments are closed.' | trans }}