您的位置:首页 > 其它

UTF-8文件头BOM的处理方法

2014-05-16 11:42 323 查看
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。

来源 http://blog.csdn.net/inkfish
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息