java String.getBytes() 和 IOUtils.toByteArray() 的区别?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13533311/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 13:07:11  来源:igfitidea点击:

Difference between String.getBytes() and IOUtils.toByteArray()?

javajunitbytearrayapache-commons

提问by Falci

I'm testing the IOUtils. I have problems to convert an InputStream into a byte array:

我正在测试 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);
}

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?

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

采纳答案by Phil K

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.

您尚未为要使用的库提供任何编码,因此将使用“默认”编码。我猜因为你的一个字节数组的大小是另一个的两倍,所以使用的一种编码是 UTF-16,另一种是 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);
}