I'm testing the IOUtils. I have problems to convert an InputStream into a byte array:
private static final String LOREM_IPSUM = "Lorem ipsum dolor sit amet, consectetur adipiscing elit.";
@Test
public void testInputStreamToByteArray() throws IOException {
byte[] expecteds = LOREM_IPSUM.getBytes();
byte[] actuals = org.apache.commons.io.IOUtils.toByteArray(new StringInputStream(LOREM_IPSUM));
assertArrayEquals(expecteds, actuals);
}
Stacktrace:
java.lang.AssertionError: array lengths differed, expected.length=56 actual.length=112
at org.junit.Assert.fail(Assert.java:91)
at org.junit.internal.ComparisonCriteria.assertArraysAreSameLength(ComparisonCriteria.java:72)
at org.junit.internal.ComparisonCriteria.arrayEquals(ComparisonCriteria.java:36)
at org.junit.Assert.internalArrayEquals(Assert.java:414)
at org.junit.Assert.assertArrayEquals(Assert.java:200)
at org.junit.Assert.assertArrayEquals(Assert.java:213)
at [...].testInputStreamToByteArray(HttpsTest.java:20)[...]
I do not see why not pass the test. What is wrong?
The method getBytes() encodes a String into a byte array using the platform's default charset if no argument is passed. We can pass a specific Charset to be used in the encoding process, either as a String object or a String object.
To convert an InputStream Object int to a String using this method. Instantiate the Scanner class by passing your InputStream object as parameter. Read each line from this Scanner using the nextLine() method and append it to a StringBuffer object. Finally convert the StringBuffer to String using the toString() method.
The IOUtils type has a static method to read an InputStream and return a byte[] . InputStream is; byte[] bytes = IOUtils. toByteArray(is); Internally this creates a ByteArrayOutputStream and copies the bytes to the output, then calls toByteArray() .
Since Java 9, we can use the readAllBytes() method from InputStream class to read all bytes into a byte array. This method reads all bytes from an InputStream object at once and blocks until all remaining bytes have read and end of a stream is detected, or an exception is thrown.
Specifying the encoding is important.
You haven't provided any encoding for the libraries to work with, and as a result the "default" encoding will be used instead. I'm guessing that since one of your byte arrays is twice the size of the other, one encoding used is UTF-16 and the other UTF-8/ASCII.
Try this:
public void testInputStreamToByteArray() throws IOException {
byte[] expecteds = LOREM_IPSUM.getBytes("UTF-8");
byte[] actuals = org.apache.commons.io.IOUtils.toByteArray(new StringReader(LOREM_IPSUM), "UTF-8");
assertArrayEquals(expecteds, actuals);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With