我正在测试 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);
}
关于java - String.getBytes() 和 IOUtils.toByteArray() 的区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13533311/