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
1.使用Java
Let’s start with the simple Java solution – going through an intermediary String:
让我们从简单的Java解决方案开始–通过一个中间的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
2.有番石榴
Next – let’s take a look at the Guava solution – also using an intermediary String:
接下来–让我们看一下Guava的解决方案–也是使用一个中间的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.
请注意,我们使用了内置的实用程序接口,不必做任何普通Java例子中的低级转换。
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支持开箱即用。
@Test
public void givenUsingCommonsIO_whenConvertingReaderIntoByteArray_thenCorrect()
throws IOException {
StringReader initialReader = new StringReader("With Commons IO");
byte[] targetArray = IOUtils.toByteArray(initialReader);
initialReader.close();
}
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.