/**
 * Date: 2008-02-18
 * Shen (http://blog.ring.idv.tw)
 **/
import java.io.*;  
import java.nio.channels.*;

public class BOMKiller
{  
	private String suffix = null;
	public BOMKiller(String suffix)
	{
		this.suffix = suffix;
	}
	
	public static void main(String arg[])
	{
		if(arg.length != 2 || (new File(arg[0])).isDirectory() == false)
		{
			System.out.println("Usage:java BOMKiller [directory_path] [suffix_name]");
			System.exit(0);
		}
		BOMKiller killer = new BOMKiller(arg[1]);
              	killer.listFiles(new File(arg[0]));
      	}
      	public void listFiles(File f)
      	{
		File[] filelist = f.listFiles(new FileFilter()
		{
			public boolean accept(File tempf)
			{
				if(tempf.isDirectory())
				{
					listFiles(tempf);
					return false;
				}
				return tempf.getName().endsWith(suffix);
			}
		});
		
          	int flength = filelist.length;
          	for(int i = 0; i < flength ; ++i)
		{  
              		killBOM(filelist[i]);
          	}
	}
	public void killBOM(File f)
	{
		try
		{
			FileInputStream fis = new FileInputStream(f);		
			if(fis.read() == 0xEF)
			{
				if(fis.read() == 0xBB)
				{
					if(fis.read()==0xBF)
					{
						String path = f.getPath();
						System.out.println("BOMKiller:"+path);
						
						File toFile = new File(path+".tmp");
						FileChannel fic = fis.getChannel();
						FileChannel foc = new FileOutputStream(toFile).getChannel();
						fic.transferTo(3, fic.size(),foc);
						fic.close();
						foc.close();
						f.delete();
						toFile.renameTo(new File(path));
					}
				}
			}
		}catch(Exception e)
		{
			e.printStackTrace();
		}
	}
}