Java 使用BOMInputStream跳过BOM,并检索不带BOM的字节[]

Java 使用BOMInputStream跳过BOM,并检索不带BOM的字节[],java,spring,byte-order-mark,Java,Spring,Byte Order Mark,我有一个带有BOM(UTF-8编码)的xml文件。该文件以字节[]的形式出现。我需要跳过BOM表,然后将这些字节转换为字符串 这就是我的代码现在的样子: BOMInputStream bomInputStream = new BOMInputStream(new ByteArrayInputStream(requestDTO.getFile())); // getFile() returns byte[] bomInputStream.skip(bomInputStream.hasBOM()

我有一个带有BOM(UTF-8编码)的xml文件。该文件以
字节[]
的形式出现。我需要跳过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
。第二个问题,我不知道以后如何从
bomInputStream
检索
byte[]
,因为
bomInputStream.getBOM().getBytes()
抛出NullPointerException。谢谢你的帮助

BOMInputStream文档链接:

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

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);
byte[]xml=requestDTO.getFile();
int bomLength=0;
Charset Charset=StandardCharsets.UTF_8;
try(BOMInputStream bommedInputStream=new BOMInputStream(new ByteArrayInputStream(xml)),
正确的){
if(bommedInputStream.hasBOM()){
bomLength=bommedInputStream.getBOM().length();
charset=charset.forName(bommedInputStream.getBOMCharsetName());
}否则{
//处理。
String t=新字符串(xml,StandardCharsets.ISO_8859_1));

String enc=t.replace((?sm)。*好的,知道了,跳过bom后如何从bomInputStream中检索字符串/字节(如果找到).第二个BOMInputStream,如您所写,或者在传递ByteArrayInputStream之前简单地使用BOM长度跳过这些字节。抱歉,我不太明白。我的意思是如何从BOMInputStream检索没有BOM的xml字节。正如我理解的
BOMInputStream.getBOM().getBytes()
如果没有BOMWill将其添加到答案中,就不会返回原始xml。好的,现在明白了