如何使用 BOM InputStream 排除 BOM [英] How to exclude BOM with BOM InputStream

查看:104
本文介绍了如何使用 BOM InputStream 排除 BOM的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图弄清楚如何在使用 Apache 给出的示例时简单地排除 BOM.我正在从 Internal Storage 读取文件,并首先将其转换为 String.然后我将它转换为 ByteArray 以便我得到一个 InputStream.然后我使用 BOMInputStream 检查 BOM,因为我有意外令牌"错误.现在我不知道如何排除 BOM(如果我有的话).

I am trying to figure out how to simply exclude the BOM while using the example given by Apache. I am reading a file from Internal Storage and converting it first into a String. Then I convert it into ByteArray so that I get an InputStream. Then I check with BOMInputStream for BOMs, since I had errors for "Unexpected Tokens". Now I don't know how to exclude the BOM if I have it.

代码:

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存储在不同的Class中.

The filename is "dataxml", which I store in different Class with openFileOutput.

推荐答案

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

You can wrap initial stream in BOMInputStream:

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

这种方式 stream 自动跳过 BOM 前缀.BOMInputStream 存在于 Apache Commons IO 库中.

This way stream skips BOM prefix automagically. BOMInputStream lives in Apache Commons IO library.

这篇关于如何使用 BOM InputStream 排除 BOM的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆