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

最后修改: 2014年 7月 9日


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


Let’s start with the simple Java example, doing the conversion via an intermediary String:


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

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


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

2. With Guava


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


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

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


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。

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

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.