Java String.getBytes()和IOUtils.toByteArray()之间的差异?

Java String.getBytes()和IOUtils.toByteArray()之间的差异?,java,junit,bytearray,apache-commons,Java,Junit,Bytearray,Apache Commons,我正在测试IOUtils。我无法将InputStream转换为字节数组: private static final String LOREM_IPSUM = "Lorem ipsum dolor sit amet, consectetur adipiscing elit."; @Test public void testInputStreamToByteArray() throws IOException { byte[] expecteds = LOREM_IPSUM.getByt

我正在测试IOUtils。我无法将InputStream转换为字节数组:

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);
}
堆栈跟踪:

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)[...]

我不明白为什么不通过考试。怎么了?

指定编码很重要。

您没有为库提供任何编码,因此将使用“默认”编码。我猜,因为一个字节数组的大小是另一个的两倍,所以使用的一种编码是UTF-16,另一种是UTF-8/ASCII

试试这个:

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);
}

谢谢但toByteArray不接受InputStream和String。两个选项:
IOUtils.toByteArray(新的StringReader(LOREM_IPSUM),“UTF-8”);IOUtils.toByteArray(新的InputStreamReader(is),“UTF-8”)啊,没有注意到您正在使用java.io.InputStream。您需要使用读卡器,或者更具体地说,使用StringReader:
byte[]actuals=org.apache.commons.io.IOUtils.toByteArray(新的StringReader(LOREM_IPSUM),“UTF-8”)我的评论只是为了澄清。再次感谢你。