有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java使用BOMInputStream跳过BOM,并检索没有BOM的字节[]

我有一个带有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。第二个,我不确定以后如何从bomInputStream检索byte[],因为bomInputStream.getBOM().getBytes()抛出NullPointerException。谢谢你的帮助

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


共 (1) 个答案

  1. # 1 楼答案

    没有布尔include参数的构造函数将排除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变体的字符集

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