Java – String to Reader – Java –字符串到阅读器

最后修改: 2014年 7月 9日


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.

在这个快速教程中,我们将看看如何将一个字符串转换为读取器,首先使用普通Java,然后是Guava,最后是Commons IO库。

This article is part of the “Java – Back to Basic” series here on Baeldung.

本文是Baeldung网站上“Java – Back to Basic “系列的一部分。

1. With Plain Java


Let’s start with the Java solution:


public void givenUsingPlainJava_whenConvertingStringIntoReader_thenCorrect() throws IOException {
    String initialString = "With Plain Java";
    Reader targetReader = new StringReader(initialString);

As you can see, the StringReader is available out of the box for this simple conversion.


2. With Guava


Next – the Guava solution:


public void givenUsingGuava_whenConvertingStringIntoReader_thenCorrect() throws IOException {
    String initialString = "With Google Guava";
    Reader targetReader = CharSource.wrap(initialString).openStream();

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

3.使用Apache Commons IO

And finally – here’s the Commons IO solution, also using a ready to go Reader implementation:

最后–这里是Commons IO解决方案,也是使用一个现成的Reader实现。

public void givenUsingCommonsIO_whenConvertingStringIntoReader_thenCorrect() throws IOException {
    String initialString = "With Apache Commons IO";
    Reader targetReader = new CharSequenceReader(initialString);

So there we have it – 3 dead simple ways to convert a String to a Reader in Java. Make sure to check out the sample over on GitHub.

因此,我们有了 – 在Java中把字符串转换为阅读器的3种简单方法。请务必查看GitHub上的样本