UTF-8 BOM又叫UTF-8 簽名,在UTF-8文件的頭部,長度爲3個字節。其實UTF-8 的BOM對UFT-8沒有作用,BOM簽名的意思就是告訴編輯器當前文件採用何種編碼,方便編輯器識別。但是在Eclipse中,帶有BOM的java源碼生成javadoc時卻會出現如下錯誤:
import java.io.File;
import java.io.IOException;
import java.util.Collection;
import org.apache.commons.io.DirectoryWalker;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
@SuppressWarnings("rawtypes")
public class Utf8BomRemover extends DirectoryWalker {
public static void main(String[] args) throws IOException {
//刪除指定文件夾下(含子文件夾)所有java文件的BOM,若構造器中參數爲null則刪除所有文件頭部BOM
new Utf8BomRemover("java").start(new File("E:/workspace/Test/src"));
}
private String extension = null;
public Utf8BomRemover(String extension) {
super();
this.extension = extension;
}
/** 啓動對某個文件夾的篩選 */
@SuppressWarnings("unchecked")
public void start(File rootDir) throws IOException {
walk(rootDir, null);
}
protected void handleFile(File file, int depth, Collection results) throws IOException {
if (extension == null
|| extension.equalsIgnoreCase(FilenameUtils.getExtension(file.toString()))) {
//調用具體業務邏輯,其實這裏不僅可以實現刪除BOM,還可以做很多想幹的事情。
remove(file);
}
}
/** 移除UTF-8的BOM */
private void remove(File file) throws IOException {
byte[] bs = FileUtils.readFileToByteArray(file);
if (bs[0] == -17 && bs[1] == -69 && bs[2] == -65) {
byte[] nbs = new byte[bs.length - 3];
System.arraycopy(bs, 3, nbs, 0, nbs.length);
FileUtils.writeByteArrayToFile(file, nbs);
System.out.println("Remove BOM: " + file);
}
}
}
在這個類中能把指定文件夾中指定後綴名的文件統一去除BOM,而整個程序源碼中沒有看到用遞歸算法,而是使用了apache commons-io,其實遞歸算法就在
DirectoryWalker
類中,實現者無需關心算法,而是關注於業務。同時,這裏給一個提醒,commons-io最新版是2.0,修改了1.4中的一些bug,其中有一處就是DirectoryWalker
類,因此建議使用最新版的commons-io。