Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/loops/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 格式错误的字节序列异常:1字节UTF-8序列的字节1无效。使用希伯来文字符时_Java_Xml_Encoding_Character Encoding - Fatal编程技术网

Java 格式错误的字节序列异常:1字节UTF-8序列的字节1无效。使用希伯来文字符时

Java 格式错误的字节序列异常:1字节UTF-8序列的字节1无效。使用希伯来文字符时,java,xml,encoding,character-encoding,Java,Xml,Encoding,Character Encoding,我试图解析包含希伯来文字符的XML文件。 我知道该文件是正确的,因为如果我输出的文件(来自不同的软件)没有希伯来文字符,它的解析就很好 我尝试了很多东西,但我总是犯这个错误 MalformedByteSequenceException: Invalid byte 1 of 1-byte UTF-8 sequence. 我最近的尝试是使用FileInputStream打开它并指定编码 DocumentBuilder db = dbf.newDocumentBuilder(); document

我试图解析包含希伯来文字符的XML文件。 我知道该文件是正确的,因为如果我输出的文件(来自不同的软件)没有希伯来文字符,它的解析就很好

我尝试了很多东西,但我总是犯这个错误

MalformedByteSequenceException: Invalid byte 1 of 1-byte UTF-8 sequence.
我最近的尝试是使用
FileInputStream
打开它并指定编码

DocumentBuilder db = dbf.newDocumentBuilder();
document = db.parse(new FileInputStream(new File(xmlFileName)), "Cp1252");
Cp1252
是一种在不同应用程序中对我有效的编码) 但我得到了同样的结果

同时尝试使用
ByteArray
,但没有任何效果


有什么建议吗?

如果您知道文件的正确编码,并且它不是“utf-8”,那么您可以将其添加到xml头中:

<?xml version="1.0" encoding="[correct encoding here]" ?>

解决方案非常简单,以UTF-8格式获取内容,并覆盖SAX输入源

File file = new File("c:\\file-utf.xml");
InputStream inputStream= new FileInputStream(file);
Reader reader = new InputStreamReader(inputStream,"UTF-8");

InputSource is = new InputSource(reader);
// is.setEncoding("UTF-8"); -> This line causes error! Content is not allowed in prolog

saxParser.parse(is, handler);

您可以在这里阅读完整的示例–

文件是如何编码的?你用什么api来解析它?我不太确定文件的编码是什么。它缺少第一行中的编码部分。。我使用的是java内置的DocumentBuilder.parse。要解析的第二个参数是系统id,而不是字符编码。我最终做到了这一点。事实上,我两次都做了,而且效果很好。谢谢
File file = new File("c:\\file-utf.xml");
InputStream inputStream= new FileInputStream(file);
Reader reader = new InputStreamReader(inputStream,"UTF-8");

InputSource is = new InputSource(reader);
// is.setEncoding("UTF-8"); -> This line causes error! Content is not allowed in prolog

saxParser.parse(is, handler);