在Windows中使用Java读取UTF-8格式的xml -file会出现"IOException:2字节UTF-8序列的无效字节2".-错误

Mik*_*nen 0 java xml parsing utf-8

我的Java程序有问题.我如何读取具有"UTF-8"编码的xml -file.程序在Kubuntu中正常工作,但我在Windows中不起作用.两个操作系统都正确编写xml -file,但解析在Windows中出现异常错误.

String XMLFile = "ÄÄKKÖSET.xml"
Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new File (XMLFile));
Run Code Online (Sandbox Code Playgroud)

这是我需要解析的xml -file:

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<deck created="04/04/2011">
  <title>ääkköset</title>
  <code>ÄÄKKÖSET</code>
  <description>ääkköset</description>
  <author>ääkköset</author>
  <cards nextCardID="1">
    <card color="#1364F9" id="0">
      <question>ÄÄKKÖSET</question>
      <answer>ÄÄKKÖSET</answer>
    </card>
  </cards>
</deck>
Run Code Online (Sandbox Code Playgroud)

如何在Windows中使用Java读取xml -file而不会得到"IOException:2字节UTF-8序列的无效字节2".-错误?

提前致谢!

McD*_*ell 5

2字节UTF-8序列的字节2无效.

您的XML文档尚未保存为UTF-8,解析器检测到这一点(因为并非所有字节序列都是合法的UTF-8)并引发错误.

解决方案是将文件保存为UTF-8.将文档声明为UTF-8是不够的 - 数据编码的字节必须与此声明匹配.默认情况下,Windows上的许多文本编辑器默认将数据保存为ANSI.