Java – InputStream to Reader – Java – InputStream to Reader

最后修改: 2014年 7月 13日

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

In this quick tutorial we’re going to take a look at converting an InputStream to a Reader using Java, then Guava and finally Apache Commons IO.

在这个快速教程中,我们将看看使用Java将InputStream转换为Reader,然后是Guava,最后是Apache Commons IO。

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

本文是Java – Back to Basic“系列的一部分,在Baeldung这里。

1. With Java

1.使用Java

First, let’s look at the simple Java solution – using the readily available InputStreamReader:

首先,让我们看一下简单的Java解决方案–使用现成的InputStreamReader

@Test
public void givenUsingPlainJava_whenConvertingInputStreamIntoReader_thenCorrect() 
  throws IOException {
    InputStream initialStream = new ByteArrayInputStream("With Java".getBytes());
    
    Reader targetReader = new InputStreamReader(initialStream);

    targetReader.close();
}

2. With Guava

2.有番石榴

Next – let’s take a look at the Guava solution – using an intermediary byte array and String:

接下来–让我们看看Guava的解决方案–使用一个中间的字节数组和String。

@Test
public void givenUsingGuava_whenConvertingInputStreamIntoReader_thenCorrect() 
  throws IOException {
    InputStream initialStream = ByteSource.wrap("With Guava".getBytes()).openStream();
    
    byte[] buffer = ByteStreams.toByteArray(initialStream);
    Reader targetReader = CharSource.wrap(new String(buffer)).openStream();

    targetReader.close();
}

Note that the Java solution is simpler than this approach.

请注意,Java的解决方案比这种方法更简单。

3. With Commons IO

3.使用Commons IO

Finally – the solution using Apache Commons IO – also using an intermediary String:

最后–使用Apache Commons IO的解决方案–也是使用一个中间的String。

@Test
public void givenUsingCommonsIO_whenConvertingInputStreamIntoReader_thenCorrect() 
  throws IOException {
    InputStream initialStream = IOUtils.toInputStream("With Commons IO");
    
    byte[] buffer = IOUtils.toByteArray(initialStream);
    Reader targetReader = new CharSequenceReader(new String(buffer));

    targetReader.close();
}

And there you have it – 3 quick ways to convert the input stream to a Java Reader. Make sure to check out the sample over on GitHub.

你已经拥有了 – 将输入流转换为Java Reader的三种快速方法。请务必查看GitHub上的样本