我试图弄清楚如何在使用Apache提供的示例时简单地排除BOM。我正在从内部存储读取一个文件,并首先将其转换为String。然后将其转换为ByteArray,以便得到一个InputStream。然后,我使用BOMInputStream检查BOMs,因为我有“意外令牌”的错误。现在我不知道如何排除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存储在不同的类中。
发布于 2017-03-09 13:22:41
您可以在BOMInputStream中包装初始流:
InputStream stream = new BOMInputStream(inputStream);
// code using stream goes here这样,stream自动跳过BOM前缀。BOMInputStream生活在Apache库中。
发布于 2014-11-25 20:58:38
我以前从未使用过BOMInputStream,但是为了从流中排除一个字节顺序标记,您只需从一个偏移量开始读取,这个偏移量比BOM结束的位置还要大。BOMInputStream是否有指示BOM位置的属性?此外,您还可以在这里查看一下:http://www.rgagnon.com/javadetails/java-handle-utf8-file-with-bom.html
发布于 2015-09-03 13:12:04
您正在构建一个从InputStream中读取字符的字符串,而忽略BOM和编码。将一个字节转换为一个字符的读取字符的方式很糟糕,非常糟糕。请使用任何阅读器的实现(指定编码)从字节序列中读取字符。
稍后,您将字符串转换回字节(在那里您需要注意指定编码。如果您比较此时获得的字节序列,它可能与从您的存储中获取的字节序列非常不同。
https://stackoverflow.com/questions/27136230
复制相似问题