将字符串转换为byte []会返回错误的值(编码?)

Tho*_*rig 5 java

byte[]从一个文件中读取一个并将其转换为String:

byte[] bytesFromFile = Files.readAllBytes(...);
String stringFromFile = new String(bytesFromFile, "UTF-8");
Run Code Online (Sandbox Code Playgroud)

我想将此与byte[]我从Web服务获得的另一个进行比较:

String stringFromWebService = webService.getMyByteString(); 
byte[] bytesFromWebService = stringFromWebService.getBytes("UTF-8");
Run Code Online (Sandbox Code Playgroud)

所以我byte[]从一个文件中读取并将其转换为a String,然后String从我的Web服务获取并将其转换为byte[].然后我做了以下测试:

// works!
org.junit.Assert.assertEquals(stringFromFile, stringFromWebService);

// fails!
org.junit.Assert.assertArrayEquals(bytesFromFile, bytesFromWebService);
Run Code Online (Sandbox Code Playgroud)

为什么第二个断言失败了?

J R*_*ape 2

其他答案涵盖了一个可能的事实,即文件未UTF-8编码,从而导致了所描述的症状。

然而,我认为最有趣的方面不是断言byte[]失败,而是assert字符串值相同通过。我不是 100% 确定这是为什么,但我认为以下对源代码的搜索可能会给我们答案:

这个假设得到了以下事实的支持: incatch的块 表示:CharacterCodingExceptionStringCoding.decode()

} catch (CharacterCodingException x) {
            // Substitution is always enabled,
            // so this shouldn't happen
Run Code Online (Sandbox Code Playgroud)