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

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

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值