簡體   English   中英

如何在Groovy中檢查文件中的UTF-8 BOM?

[英]How to check for UTF-8 BOM in files in Groovy?

  • 我不想將整個文件加載到內存中
  • 我不想對底層操作系統做任何假設。

我剩下這個:

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.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"
    }
}

好吧,Groovy使用Java庫,對此有一個Java解決方案:Apache Common IO。

您可以看一下該線程的答案:

讀取UTF-8-BOM標記

該線程中與Apache Common IO的鏈接不再起作用,這是正確的鏈接:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM