1. Introduction
In this article, we are going to present various ways to convert String to Reader in Java. We will use plain Java
solution and external libraries such as Guava
and Apache Commons IO
. String to Reader conversion is pretty natural, because Readers
are character-based streams.
If you are looking for more Java I/O articles, check the following links:
2. Convert String to Reader using plain Java
Let's take a look at a pure Java solution:
As you can see plain Java provides a simple one-line solution to this kind of conversions. In this example, we used StringReader
which extends the Reader
class and provides all the necessary methods.
3. String to Reader with Guava
To convert String
to Reader
we can also use Guava
library, that provides many utility classes for I/O operations:
In this example, we used CharSource
class that wraps given String
and create character-based stream out of it.
4. String to Reader using Apache Commons IO
library
The Apache Commons IO
library also comes with a straightforward solution for this kind of conversion:
This example used CharSequenceReader
class (that extends an abstract Reader
class) that wraps given String
.
5. Conclusion
In this article, we presented three ways to convert String to Reader using plain Java, Guava, and Apache Commons IO library. These three solutions are simple and straightforward.
All examples used in this tutorial are available under our GitHub repository.
{{ 'Comments (%count%)' | trans {count:count} }}
{{ 'Comments are closed.' | trans }}