Java – Byte Array to Reader – Java – 字节数组到阅读器

最后修改: 2014年 7月 9日

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

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

在这个快速教程中,我们将使用普通的Java、Guava和最后的Apache 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 simple Java example, doing the conversion via an intermediary String:

让我们从简单的Java例子开始,通过一个中间的String做转换。

@Test
public void givenUsingPlainJava_whenConvertingByteArrayIntoReader_thenCorrect() 
  throws IOException {
    byte[] initialArray = "With Java".getBytes();
    Reader targetReader = new StringReader(new String(initialArray));
    targetReader.close();
}

An alternative approach would be to make use of an InputStreamReader and a ByteArrayInputStream:

另一种方法是利用一个InputStreamReader和一个ByteArrayInputStream

@Test
public void givenUsingPlainJava2_whenConvertingByteArrayIntoReader_thenCorrect() 
  throws IOException {
    byte[] initialArray = "Hello world!".getBytes();
    Reader targetReader = new InputStreamReader(new ByteArrayInputStream(initialArray));
    targetReader.close();
}

2. With Guava

2.有番石榴

Next – let’s take a look at the Guava solution, also using an intermediary String:

接下来–让我们看看Guava的解决方案,也是使用一个中间的String。

@Test
public void givenUsingGuava_whenConvertingByteArrayIntoReader_thenCorrect() 
  throws IOException {
    byte[] initialArray = "With Guava".getBytes();
    String bufferString = new String(initialArray);
    Reader targetReader = CharSource.wrap(bufferString).openStream();
    targetReader.close();
}

Unfortunately the Guava ByteSource utility doesn’t allow a direct conversion, so we still need to use the intermediary String representation.

不幸的是,Guava的ByteSource工具不允许直接转换,所以我们仍然需要使用中间的String表示。

3. With Apache Commons IO

3.使用Apache Commons IO

Similarly – Commons IO also uses an intermediary String representation to convert the byte[] to a Reader:

类似地–Commons IO也使用一个中间的String表示法,将byte[]转换为Reader。

@Test
public void givenUsingCommonsIO_whenConvertingByteArrayIntoReader_thenCorrect() 
  throws IOException {
    byte[] initialArray = "With Commons IO".getBytes();
    Reader targetReader = new CharSequenceReader(new String(initialArray));
    targetReader.close();
}

And there we have it – 3 simple ways to convert the byte array into a Java Reader. Make sure to check out the sample over on GitHub.

这就是我们所拥有的–将字节数组转换为Java阅读器的3种简单方法。请务必查看GitHub上的样本