Java – Byte Array to Writer – Java –字节数组到写入器

最后修改: 2016年 4月 8日

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

1. Overview

1.概述

In this very quick tutorial, we’ll discuss how to convert byte[] to Writer using plain Java, Guava and Commons IO.

在这个非常快速的教程中,我们将讨论如何使用普通Java、Guava和Commons IO将byte[]转换为Writer

2. With Plain Java

2.使用普通的Java

Let’s start with a simple Java solution:

让我们从一个简单的Java解决方案开始。

@Test
public void givenPlainJava_whenConvertingByteArrayIntoWriter_thenCorrect() 
  throws IOException {
    byte[] initialArray = "With Java".getBytes();
    Writer targetWriter = new StringWriter().append(new String(initialArray));

    targetWriter.close();
    
    assertEquals("With Java", targetWriter.toString());
}

Note that we converted our byte[] into a Writer through an intermediate String.

请注意,我们通过一个中间的String将我们的byte[]转换成Writer

3. With Guava

3.有番石榴

Next – let’s look into a more complex solution with Guava:

接下来–让我们看看用Guava做的更复杂的解决方案。

@Test
public void givenUsingGuava_whenConvertingByteArrayIntoWriter_thenCorrect() 
  throws IOException {
    byte[] initialArray = "With Guava".getBytes();

    String buffer = new String(initialArray);
    StringWriter stringWriter = new StringWriter();
    CharSink charSink = new CharSink() {
        @Override
        public Writer openStream() throws IOException {
            return stringWriter;
        }
    };
    charSink.write(buffer);

    stringWriter.close();

    assertEquals("With Guava", stringWriter.toString());
}

Note that here, we converted the byte[] into a Writer by using a CharSink.

注意,在这里,我们通过使用CharSinkbyte[]转换成Writer

4. With Commons IO

4.使用Commons IO

Finally, let’s check our Commons IO solution:

最后,让我们检查一下我们的Commons IO解决方案。

@Test
public void givenUsingCommonsIO_whenConvertingByteArrayIntoWriter_thenCorrect() 
  throws IOException {
    byte[] initialArray = "With Commons IO".getBytes();
    
    Writer targetWriter = new StringBuilderWriter(
      new StringBuilder(new String(initialArray)));

    targetWriter.close();

    assertEquals("With Commons IO", targetWriter.toString());
}

Note: We converted our byte[] to StringBuilderWriter using a StringBuilder.

注意:我们将我们的byte[]转换为StringBuilderWriter使用StringBuilder

5. Conclusion

5.结论

In this short and to the point tutorial, we illustrated 3 different ways to convert a byte[] into a Writer.

在这个短小精悍的教程中,我们说明了将byte[]转换成Writer的3种不同方式。

The code for this article is available in the GitHub repository.

本文的代码可在GitHub资源库中找到。