文档解析期间 4 字节 UTF-8 序列中的字节 2 无效



我正在尝试从字节解析文档,如下所示

String result = /* some valid xml document */
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder parser = factory.newDocumentBuilder();
try {
Document document = parser.parse(new ByteArrayInputStream(result.getBytes()));
} catch (MalformedByteSequenceException e) {
System.out.println("(MalformedByteSequenceException ) " + e.getMessage());
}

抛出格式错误的字节序列异常,并在控制台中打印下一个

"(MalformedByteSequenceException ) Invalid byte 2 of 4-byte UTF-8 sequence."

奇怪的是,相同的代码在我的本地环境(Windows 10(中有效,但在远程环境(Windows Server 2012(中无效。

我试图在我的本地环境中复制错误,将 TomEE 版本从 1.7.4 更改为 1.7.1,我尝试将 JRE 从 1.7.0_80 更改为 1.7.0,我尝试将完整的 Tomee 文件夹从远程系统复制到我的本地机器,但错误只发生在远程环境中

使用result.getBytes(Charset.forName("UTF-8"))而不是result.getBytes()也不起作用。

我找到了解决方案。在setenv.bat的开头设置它,

rem Set encoding
set JAVA_OPTS=%JAVA_OPTS% -Dfile.encoding=UTF-8

我不确定这背后的基本原理,但似乎 JVM 正在使用一些奇怪的 Windows 编码而不是您需要的 UTF-8

调用String.getBytes()与调用String.getBytes("<value of file.encoding>")完全相同。

但是,根本不需要这么称呼。使用在StringReader上设置InputSource呼叫parse

相关内容

最新更新