【问题标题】:How to exclude BOM with BOM InputStream如何使用 BOM InputStream 排除 BOM
【发布时间】:2014-11-25 20:38:16
【问题描述】:

我试图弄清楚如何在使用 Apache 给出的示例时简单地排除 BOM。 我正在从 Internal Storage 读取一个文件,并首先将其转换为 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存储在不同的类中。

【问题讨论】:

    标签: java android xml xml-parsing byte-order-mark


    【解决方案1】:

    您可以将初始流包装在 BOMInputStream 中:

        InputStream stream = new BOMInputStream(inputStream);
        // code using stream goes here
    

    这样stream 会自动跳过 BOM 前缀。 BOMInputStream 存在于 Apache Commons IO 库中。

    【讨论】:

    • BOMInputStream!你这辈子都去哪儿了?!
    【解决方案2】:

    我以前从未使用过 BOMInputStream,但要从流中排除字节顺序标记,您只需从比 BOM 结尾位置大一的偏移量开始读取。 BOMInputStream 是否具有指示 BOM 位置的属性? 另外,你可以看看这里:http://www.rgagnon.com/javadetails/java-handle-utf8-file-with-bom.html

    【讨论】:

    • 我目前正在考虑其他事情。是否可以只使用 FileInputStream 作为 XmlParser 的 InputStream?
    • 绝对可以。我注意到您一次读取 1 个字符,因此您可以在 BOM 进入时对其进行识别,并且仅在您读取最后一个 BOM 字符时附加。 (顺便说一句,您可以阅读更大的块,例如 4096,但这将无法找到 bom)
    • 我将发布另一个问题,因为如果在 m 情况下没有必要,我不想使用 BOM。我已经在内部存储中存储了一个文件。现在我使用 FileInputStream 打开它。为什么我的 XMLPULLPARSER 不能识别它?在我的应用程序中,我放置了一个需要在文件中找到的单词。我知道 Word 存在,但应用程序没有返回它找到它。
    【解决方案3】:

    您正在构建一个从 InputStream 读取字符的字符串,而不考虑 BOM 和编码。您从将一个字节转换为一个字符的蒸汽中读取字符的方式很糟糕,非常糟糕。请使用 Reader 的任何实现(指定编码)从字节序列中读取字符。

    稍后您将字符串转换回字节(并且您需要注意指定编码。如果您比较此时获得的字节序列,它可能与您从商店获取的字节序列非常不同。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-01-28
      • 2021-12-21
      • 1970-01-01
      • 2011-12-13
      • 1970-01-01
      • 2013-09-25
      • 2014-03-20
      相关资源
      最近更新 更多