使用BOMInputStream跳过BOM表并检索不带BOM的byte []

问题描述

我有一个带BOM(UTF-8编码)的xml文件。该文件以byte[]的形式出现。我需要跳过BOM表,然后再将这些字节转换为字符串。

这是我的代码现在的样子:

BOMInputStream bomInputStream = new BOMInputStream(new ByteArrayInputStream(requestDTO.getFile())); // getFile() returns byte[]

bomInputStream.skip(bomInputStream.hasBOM() ? bomInputStream.getBOM().length() : 0);

validationService.validate(new String(/*BYTE[] WITHOUT BOM*/)); // throws NullPointerException

我正在使用BOMInputStream。我有几个问题。第一个是bomInputStream.hasBOM()返回false。第二个,我不确定以后如何从byte[]检索bomInputStream,因为bomInputStream.getBOM().getBytes()抛出NullPointerException。感谢您的帮助!

BOMInputStream文档链接: https://commons.apache.org/proper/commons-io/javadocs/api-2.5/org/apache/commons/io/input/BOMInputStream.html

解决方法

没有布尔值包含参数的构造函数将BOM排除在外,因此hasBOM()返回false,并且不会包含BOM。并且该字符串将不包含BOM。 然后getBOM()返回null!

byte[] xml = requestDTO.getFile();
int bomLength = 0;
Charset charset = StandardCharsets.UTF_8;
try (BOMInputStream bommedInputStream = new BOMInputStream(new ByteArrayInputStream(xml),true)) {
    if (bommedInputStream.hasBOM()) {
        bomLength = bommedInputStream.getBOM().length();
        charset = Charset.forName(bommedInputStream.getBOMCharsetName());
    } else {
        // Handle <?xml ... encoding="..." ... ?>.
        String t = new String(xml,StandardCharsets.ISO_8859_1));
        String enc = t.replace("(?sm).*<\\?xml.*\\bencoding=\"([^\"]+)\".*\\?>.*$","$1");
        ... or such to fill charset ...
    }
}
String s = new String(xml,charset).replaceFirst("^\uFEFF",""); // Remove BOM.
validationService.validate(s);

可以使用bomLength删除BOM。 BOMInputStream可以为我们提供许多UTF变体的字符集。

不带编码/字符集的String构造函数(如您所用)将使用默认平台编码。因为BOM是Unicode代码指针U + FEFF,所以只需传递"\uFEFF"

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...