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

最后修改: 2014年 7月 12日

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

In this quick tutorial we’re going to convert a Reader into a String using plain Java, Guava and the Apache Commons IO library.

在这个快速教程中,我们将使用普通的Java、Guava和Apache Commons IO库将一个Reader转换为一个String。

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

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

1. With Java

1.使用Java

Let’s start with a simple Java solution that reads characters sequentially from the Reader:

让我们从一个简单的Java解决方案开始,Reader按顺序读取字符。

@Test
public void givenUsingPlainJava_whenConvertingReaderIntoStringV1_thenCorrect() 
  throws IOException {
    StringReader reader = new StringReader("text");
    int intValueOfChar;
    String targetString = "";
    while ((intValueOfChar = reader.read()) != -1) {
        targetString += (char) intValueOfChar;
    }
    reader.close();
}

If there is a lot of content to read, a bulk-read solution will work better:

如果有大量的内容需要阅读,批量阅读的解决方案会更有效。

@Test
public void givenUsingPlainJava_whenConvertingReaderIntoStringV2_thenCorrect() 
  throws IOException {
    Reader initialReader = new StringReader("text");
    char[] arr = new char[8 * 1024];
    StringBuilder buffer = new StringBuilder();
    int numCharsRead;
    while ((numCharsRead = initialReader.read(arr, 0, arr.length)) != -1) {
        buffer.append(arr, 0, numCharsRead);
    }
    initialReader.close();
    String targetString = buffer.toString();
}

2. With Guava

2.有番石榴

Guava provides a utility that can do the conversion directly:

Guava提供了一个工具,可以直接进行转换

@Test
public void givenUsingGuava_whenConvertingReaderIntoString_thenCorrect() 
  throws IOException {
    Reader initialReader = CharSource.wrap("With Google Guava").openStream();
    String targetString = CharStreams.toString(initialReader);
    initialReader.close();
}

3. With Commons IO

3.使用Commons IO

Same with Apache Commons IO – there is an IO utility capable of performing the direct conversion:

与Apache Commons IO相同 – 有一个IO工具能够进行直接转换

@Test
public void givenUsingCommonsIO_whenConvertingReaderIntoString_thenCorrect() 
  throws IOException {
    Reader initialReader = new StringReader("With Apache Commons");
    String targetString = IOUtils.toString(initialReader);
    initialReader.close();
}

And there you have it – 4 ways of transforming a Reader into a plain String. Make sure to check out the sample over on GitHub.

这就是你所拥有的–将Reader转换为普通字符串的4种方法。请确保查看GitHub上的样本