我试图弄清楚如何使用Apache给出的示例简单地排除BOM。
我正在从内部存储读取文件,然后先将其转换为String。然后将其转换为ByteArray,以便获得InputStream。然后我用BOMInputStream检查BOM表,因为我遇到了“意外令牌”错误。现在,我不知道如何排除BOM(如果有)。

码:

StringBuffer fileContent = new StringBuffer("");
String temp = "";
int ch;
try{
    FileInputStream fis = ctx.openFileInput("dataxml");
try {
    while( (ch = fis.read()) != -1)
        fileContent.append((char)ch);
        temp = temp + Character.toString((char)ch);
} catch (IOException e) {
    e.printStackTrace();
}
} catch (FileNotFoundException e) {
    e.printStackTrace();
}


InputStream ins = new ByteArrayInputStream(temp.getBytes(StandardCharsets.UTF_8));
BOMInputStream bomIn = new BOMInputStream(ins);
if (bomIn.hasBOM()) {
    // has a UTF-8 BOM

}

xpp.setInput(ins,"UTF-8");
parseXMLAndStoreIt(xpp);
ins.close();


文件名是“ dataxml”,我用openFileOutput存储在不同的类中。

最佳答案

您可以使用BOMInputStream删除BOM,如下所示:

BOMInputStream bis = new BOMInputStream(inputStream);
        if (bis.hasBOM()) {
           bis.skip(bis.getBOM().length());
        }


如果不起作用,您可以调整跳过参数。就我而言,我有以下解决方案:

  bis.skip(bis.getBOM().length()-3);

07-24 15:49