This quick tutorial will show how to convert a Reader into a byte[] using plain Java, Guava and the Apache Commons IO library.
This article is part of the βJava β Back to Basicβ series here on Baeldung.
1. With Java
Letβs start with the simple Java solution β going through an intermediary String:
@Test
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 = initialReader.read(charArray, 0, charArray.length)) != -1) {
builder.append(charArray, 0, numCharsRead);
}
byte[] targetArray = builder.toString().getBytes();
initialReader.close();
}
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:
@Test
public void givenUsingGuava_whenConvertingReaderIntoByteArray_thenCorrect()
throws IOException {
Reader initialReader = CharSource.wrap("With Google Guava").openStream();
byte[] targetArray = CharStreams.toString(initialReader).getBytes();
initialReader.close();
}
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
And finally β hereβs a direct solution that is supported out of the box with Commons IO:
@Test
public void givenUsingCommonsIO_whenConvertingReaderIntoByteArray_thenCorrect()
throws IOException {
StringReader initialReader = new StringReader("With Commons IO");
byte[] targetArray = IOUtils.toByteArray(initialReader);
initialReader.close();
}
