Unterschied zwischen String.getBytes() und IOUtils.toByteArray()?
Teste ich die IOUtils. Ich habe Probleme bei der Umwandlung eines InputStream in ein 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)[...]
Ich sehe nicht ein, warum die Prüfung nicht bestanden. Was ist falsch?
Du musst angemeldet sein, um einen Kommentar abzugeben.
Die Angabe der Kodierung ist wichtig.
Du zur Verfügung gestellt hast Codierung für die Bibliotheken, mit zu arbeiten, und als Ergebnis die "default" - Codierung verwendet werden, statt. Ich vermute, dass da einer Ihrer byte-arrays, die zweimal so groß ist wie die andere, man verwendete Codierung ist UTF-16 und die anderen UTF-8/ASCII.
Versuchen Sie dies:
IOUtils.toByteArray (new StringReader (LOREM_IPSUM), "UTF-8"); IOUtils.toByteArray (new InputStreamReader (is), "UTF-8");
byte[] actuals = org.apache.commons.io.IOUtils.toByteArray(new StringReader(LOREM_IPSUM), "UTF-8");