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

最后修改: 2014年 7月 12日

This quick tutorial will show how to convert a Reader into a byte[] using plain Java, Guava and the Apache Commons IO library.

这个快速教程将展示如何使用普通的Java、Guava和Apache Commons IO库将Reader转换为byte[]

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

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

1. With Java


Let’s start with the simple Java solution – going through an intermediary String:


public void givenUsingPlainJava_whenConvertingReaderIntoByteArray_thenCorrect() 
  throws IOException {
    Reader initialReader = new StringReader("With Java");

    char[] charArray = new char[8 * 1024];
    StringBuilder builder = new StringBuilder();
    int numCharsRead;
    while ((numCharsRead =, 0, charArray.length)) != -1) {
        builder.append(charArray, 0, numCharsRead);
    byte[] targetArray = builder.toString().getBytes();


Note that the reading is done in chunks, not one character at a time.


2. With Guava


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


public void givenUsingGuava_whenConvertingReaderIntoByteArray_thenCorrect() 
  throws IOException {
    Reader initialReader = CharSource.wrap("With Google Guava").openStream();

    byte[] targetArray = CharStreams.toString(initialReader).getBytes();


Notice that we’re using the built in utility API to not have to do any of the low-level conversion of the plain Java example.


3. With Commons IO

3.使用Commons IO

And finally – here’s a direct solution that is supported out of the box with Commons IO:

最后–这里有一个直接的解决方案,Commons IO支持开箱即用。

public void givenUsingCommonsIO_whenConvertingReaderIntoByteArray_thenCorrect() 
  throws IOException {
    StringReader initialReader = new StringReader("With Commons IO");

    byte[] targetArray = IOUtils.toByteArray(initialReader);


And there you have it – 3 quick ways to transform a java Reader into a byte array. Make sure to check out the sample over on GitHub.

你已经拥有了 – 3种快速将java Reader转换为字节数组的方法。请务必查看GitHub上的样本