我试图弄清楚如何在使用 Apache 给出的示例时简单地排除 BOM。
我正在从内部存储读取文件,并首先将其转换为字符串
。然后我将其转换为 ByteArray
,以便获得 InputStream
。然后我使用 BOMInputStream
检查 BOM,因为我遇到了“意外 token ”错误。 现在我不知道如何排除 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 中:
InputStream stream = new BOMInputStream(inputStream);
// code using stream goes here
这样stream
会自动跳过BOM前缀。 BOMInputStream
存在于 Apache Commons IO 库中。
关于java - 如何使用 BOM 输入流排除 BOM,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27136230/