In this quick tutorial weβll take a look at how to convert a String to a Reader ,first using plain Java then Guava and finally the Commons IO library.
This article is part of the βJava β Back to Basicβ series here on Baeldung.
1. With Plain Java
Letβs start with the Java solution:
@Test
public void givenUsingPlainJava_whenConvertingStringIntoReader_thenCorrect() throws IOException {
String initialString = "With Plain Java";
Reader targetReader = new StringReader(initialString);
targetReader.close();
}
As you can see, the StringReader is available out of the box for this simple conversion.
2. With Guava
Next β the Guava solution:
@Test
public void givenUsingGuava_whenConvertingStringIntoReader_thenCorrect() throws IOException {
String initialString = "With Google Guava";
Reader targetReader = CharSource.wrap(initialString).openStream();
targetReader.close();
}
Weβre making use here of the versatile CharSource abstraction that allows us to open up a Reader from it.
3. With Apache Commons IO
And finally β hereβs the Commons IO solution, also using a ready to go Reader implementation:
@Test
public void givenUsingCommonsIO_whenConvertingStringIntoReader_thenCorrect() throws IOException {
String initialString = "With Apache Commons IO";
Reader targetReader = new CharSequenceReader(initialString);
targetReader.close();
}
