Course – LS (cat=Java)

Get started with Spring 5 and Spring Boot 2, through the Learn Spring course:


1. Overview

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

2. With Plain Java

Let’s start with a simple Java solution:

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

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

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

3. With Guava

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

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() {
        public Writer openStream() throws IOException {
            return stringWriter;


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

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

4. With Commons IO

Finally, let’s check our Commons IO solution:

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


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

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

5. Conclusion

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

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

Course – LS (cat=Java)

Get started with Spring 5 and Spring Boot 2, through the Learn Spring course:

res – REST with Spring (eBook) (everywhere)
Comments are closed on this article!