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:
@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.
3. With Guava
Next – let’s look into a more complex solution with 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.
4. With Commons IO
Finally, let’s check our Commons IO solution:
@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.
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.