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

最后修改: 2014年 7月 9日

中文/混合/英文(键盘快捷键:t)

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

1.使用普通的Java

Let’s start with the Java solution:

让我们从Java的解决方案开始。

@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.

正如你所看到的,StringReader可以开箱即用,用于这种简单的转换。

2. With Guava

2.有番石榴

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.

我们在这里利用了多功能的CharSource抽象,允许我们从中打开一个Reader。

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实现。

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

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上的样本