【问题标题】:How to check for UTF-8 BOM in files in Groovy?如何在 Groovy 中检查文件中的 UTF-8 BOM?
【发布时间】:2013-12-04 23:06:03
【问题描述】:
  • 我不想将整个文件加载到内存中
  • 我不想对底层操作系统做任何假设。

我只剩下这个了:

echo it, "Checking file.. ${file.absolutePath}"
def fis = new FileInputStream(file)
def openingBytes = new byte[3]
try {
    fis.read(openingBytes)

    if (openingBytes.encodeHex() =~ /^efbbbf/) {
        errors << file.path + " - File needs to be converted from UTF-8 BOM to UTF-8 without BOM"
    }
} catch (Exception e) {
    errors << "Encountered an error trying to check " + file.path + " for BOMs."
} finally {
    fis.close()
}

但这看起来非常冗长且类似于 Java。 :-(

【问题讨论】:

    标签: file utf-8 groovy byte byte-order-mark


    【解决方案1】:

    怎么样:

    file.withInputStream { fis ->
        byte[] openingBytes = new byte[3]
        fis.read( openingBytes )
        if( openingBytes != [ 0xEF, 0xBB, 0xBF ] as byte[] ) {
            errors << file.path + " - File needs to be converted from UTF-8 BOM to UTF-8 without BOM"
        }
    }
    

    【讨论】:

    • 绝对更好:-)
    【解决方案2】:

    好吧,Groovy 使用 Java 库,对此有一个 Java 解决方案:Apache Common IO。

    你可以看看这个帖子的答案:

    Reading UTF-8 - BOM marker

    链接到该线程中的 Apache Common IO 不再有效,这是正确的链接:

    http://commons.apache.org/proper/commons-io/apidocs/org/apache/commons/io/input/BOMInputStream.html

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-12-27
      • 2017-05-08
      • 2011-05-22
      • 2020-07-07
      • 2012-02-12
      相关资源
      最近更新 更多