ファイル任意符号化変換ツールExecuteConvertFile


プロジェクトでは複数箇所のファイルを引用しているが、符号化方式が統一されておらず、gb 2312、gbk、gb 18030、ascii、utf-8などがあり混乱している.
 
ネット上でいくつかの符号化変換ツールを探しましたが、理想的ではありません.そこで自分でコード変換のツールを書きました.指定したテキストタイプのソースファイルまたはディレクトリ内のすべての指定したテキストタイプのサブファイルを指定した符号化タイプに変換し、パス構造でターゲットディレクトリの下に保存できます.他の非テキストタイプのファイルは、直接コピーして保存します.
 
ファイルの符号化タイプを取得するためにmozillaの符号化クエリーを参照するパケット.
 
以下は主なコードです:(jarパッケージは添付ファイルにあります)
 
インタフェース:ConvertEncoding.JAva符号化変換
/**
 * FileName:EncodingConvert.java
 * Creater: Landry
 * Create Date:2010-3-15
 * Commonents:
 * Version: 1.0
 */
package com.landry.encoding;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;

/**
 * Project:ConvertTxtEncoding
 * Create Dat:2010-3-15
 * Modified Date:
 * Commonents:           
 * @author Landry
 * @version 1.0
 */
public interface ConvertEncoding
{
	/**
	 *          
	 * @param file
	 * @return        
	 * @throws FileNotFoundException
	 * @throws IOException
	 */
	public String getFileCharacter (File file) throws FileNotFoundException,
			IOException;
	
	/**
	 *                
	 * @param file
	 * @return true:         false:         
	 */
	public boolean isTextFile (File file);
	
	/**
	 *              (   ), "<b>|</b>"    <br/>
	 *       ,            :txt、ini、java、jsp、jspa、htm、html、xml、js、vbs、css、properties、ftl、php、asp
	 * @param fileExtName
	 */
	public void setInclude (String fileExtName);

	/**
	 *         
	 * @param file
	 * @return null         ,     
	 */
	public String getFileExtName (File file);
	
	/**
	 *  encoding       ,          
	 * @param inFilename
	 * @param outFilename
	 * @param encoding
	 * @throws IOException
	 * @throws FileNotFoundException
	 */
	public void convertEncoding (String inFilename, String outFilename,
			String encoding) throws FileNotFoundException, IOException;
	
	/**
	 *             
	 * @param inFilename
	 * @param outFilename
	 * @param encoding
	 * @throws IOException
	 * @throws FileNotFoundException
	 */
	public void convertEncodingProcess (String inFilename, String outFilename,
			String encoding) throws FileNotFoundException, IOException;
	
	/**
	 *         
	 * @param inFilename
	 * @param outFilename
	 * @throws FileNotFoundException
	 * @throws IOException
	 */
	public void copyBinaryFile (String inFilename, String outFilename)
			throws FileNotFoundException, IOException;
}

 ExecuteConvertFile.JAva実行ファイルの変換保存
/**
 * FileName:ExecuteFile.java
 * Creater: Landry
 * Create Date:2010-3-17
 * Commonents:
 * Version: 1.0
 */
package com.landry.encoding;

import java.io.FileNotFoundException;
import java.io.IOException;

/**
 * Project:ConvertTxtEncoding
 * Create Dat:2010-3-17
 * Modified Date:
 * Commonents:
 * @author Landry
 * @version 1.0
 */
public interface ExecuteConvertFile
{
	/**
	 *         
	 * 1、inFilename      ,outFilename     ,        ;
	 *        ,      
	 * 2、inFilename    ,outFilename     ,                   
	 * @param inFilename     
	 * @param outFilename      
	 * @param encoding        
	 * @throws FileNotFoundException
	 * @throws IOException
	 */
	public void executeConvertFile (String inFilename, String outFilename,
			String encoding) throws FileNotFoundException, IOException;

	/**
	 *              (   ), "|"    
	 *       ,            :txt、ini、java、jsp、jspa、htm、html、xml、js、vbs、css、properties、ftl、php、asp
	 * @param fileExtName
	 */
	public void setInclude (String fileExtName);
}

 
実装クラス:ConvertEncodingImpl.java
/**
 * FileName:EncodingConvertImpl.java
 * Creater: Landry
 * Create Date:2010-3-15
 * Commonents:
 * Version: 1.0
 */
package com.landry.encoding;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.HashSet;

/**
 * Project:ConvertTxtEncoding
 * Create Dat:2010-3-15
 * Modified Date:
 * Commonents:
 * @author Landry
 * @version 1.0
 */
public class ConvertEncodingImpl implements ConvertEncoding
{
	/**            */
	HashSet<String> include = new HashSet<String>();
	private final String defaultIncludeFile = "txt|ini|java|jsp|jspa|htm|html|xml|js|vbs|css|properties|ftl|php|asp";
	
	public ConvertEncodingImpl ()
	{
		//               ,          
		if (include.isEmpty())
		{
			setInclude(defaultIncludeFile);
		}
	}
	
	@Override
	public void setInclude (String fileExtName)
	{
		String[] arr = fileExtName.split("\\|");
		for (String name : arr)
		{
			include.add(name.trim());
		}
	}
	
	@Override
	public void convertEncoding (String inFilename, String outFilename,
			String encoding) throws FileNotFoundException, IOException
	{
		//    
		File inFile = new File(inFilename);
		if (!inFile.exists())
		{
			System.out.println(inFile.getAbsolutePath() + "   ");
			return;
		}
		//     
		File outFile = new File(outFilename);
		
		if (inFile.isDirectory())//         ,             
		{
			outFile.mkdirs();
			return;
		}
		else
		{
			outFile.createNewFile();
			boolean isTxt = isTextFile(inFile);
			if (isTxt)//        ,      
				convertEncodingProcess(inFilename, outFilename, encoding);
			else
				//         ,    
				copyBinaryFile(inFilename, outFilename);
		}
	}
	
	@Override
	public void convertEncodingProcess (String inFilename, String outFilename,
			String encoding) throws FileNotFoundException, IOException
	{
		File inFile = new File(inFilename);
		String currentEncoding = getFileCharacter(inFile);
		File outFile = new File(outFilename);
		
		BufferedReader reader = new BufferedReader(new InputStreamReader(
				new FileInputStream(inFile), currentEncoding));
		BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(
				new FileOutputStream(outFile), encoding));

		String str = "";
		while ((str = reader.readLine()) != null)
		{
			writer.write(str + "\r
"); } writer.flush(); reader.close(); writer.close(); } @Override public void copyBinaryFile (String inFilename, String outFilename) throws FileNotFoundException, IOException { File inFile = new File(inFilename); File outFile = new File(outFilename); BufferedInputStream bis = new BufferedInputStream(new FileInputStream( inFile)); BufferedOutputStream bos = new BufferedOutputStream( new FileOutputStream(outFile)); byte[] data = new byte[1]; while (bis.read(data) != -1) { bos.write(data); } bos.flush(); bis.close(); bos.close(); } @Override public String getFileCharacter (File file) throws FileNotFoundException, IOException { CharsetDetector charDect = new CharsetDetector(); FileInputStream fis = new FileInputStream(file); String[] probableSet = charDect.detectChineseCharset(fis); if (probableSet.length == 1) { if (probableSet[0].equals("x-euc-tw")) { return "GB2312"; } else { return probableSet[0]; } } else if (probableSet.length > 1) { for (String character : probableSet) { if (character.equals("GB2312")) return "GB2312"; if (character.equals("UTF-8")) return "UTF-8"; if (character.equals("ASCII")) return "ASCII"; } } return null; } @Override public String getFileExtName (File file) { if (file.isDirectory()) return null; String fullName = file.getName(); int index = fullName.indexOf("."); return fullName.substring(index + 1); } @Override public boolean isTextFile (File file) { String extName = getFileExtName(file); return include.contains(extName); } }

 ExecuteConvertFileImpl.java
/**
 * FileName:ExecuteConvertFileImpl.java
 * Creater: Landry
 * Create Date:2010-3-17
 * Commonents:
 * Version: 1.0
 */
package com.landry.encoding;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;

/**
 * Project:ConvertTxtEncoding
 * Create Dat:2010-3-17
 * Modified Date:
 * Commonents:
 * @author Landry
 * @version 1.0
 */
public class ExecuteConvertFileImpl implements ExecuteConvertFile
{
	/**         */
	private File srcFile;
	/**           */
	private File targetFile;
	/**       */
	private final String separator = System.getProperties().getProperty(
			"file.separator");
	final ConvertEncoding convertEncoding = new ConvertEncodingImpl();

	@Override
	/**
	 *              (   ), "|"    
	 *       ,            :txt、ini、java、jsp、jspa、htm、html、xml、js、vbs、css、properties、ftl、php、asp
	 * @param fileExtName
	 */
	public void setInclude (String fileExtName)
	{
		convertEncoding.setInclude(fileExtName);
	}

	@Override
	public void executeConvertFile (String inFilename, String outFilename,
			String encoding) throws FileNotFoundException, IOException
	{
		srcFile = new File(inFilename);
		targetFile = new File(outFilename);
		if (!srcFile.exists())
		{
			System.out.println("      :" + srcFile.getAbsolutePath());
			return;
		}
		execute(inFilename, outFilename, encoding);
	}
	
	/**
	 *            
	 * @param inFilename
	 * @param outFilename
	 * @param encoding
	 * @throws IOException
	 * @throws FileNotFoundException
	 */
	private void execute (String inFilename, String outFilename, String encoding)
			throws FileNotFoundException, IOException
	{
		File inFile = new File(inFilename);
		if (!inFile.isDirectory())//       ,      
		{
			convertEncoding.convertEncoding(inFilename, outFilename, encoding);//          
		}
		else
		{

			File outFile = new File(outFilename);
			outFile.mkdirs();//           

			String[] fileList = inFile.list();//            
			for (String childFilename : fileList)
			{
				String srcChildFilename = getCurSrcFilename(inFile,
						childFilename);
				String targetChildFilename = getCurTargetFilename(inFile,
						childFilename);
				//     ,       
				execute(srcChildFilename, targetChildFilename, encoding);

			}
		}
	}
	
	/**
	 *            
	 * @param parent    
	 * @param childFilename
	 * @return
	 */
	private String getCurSrcFilename (File parent, String childFilename)
	{
		return parent.getAbsoluteFile() + separator + childFilename;
	}
	
	/**
	 *             
	 * @param parent    
	 * @param childFilename
	 * @return
	 */
	private String getCurTargetFilename (File parent, String childFilename)
	{
		String parentFilename = parent.getAbsolutePath();
		int index = srcFile.getAbsolutePath().length();
		String relativePath = parentFilename.substring(index);
		String curTargetFilename = targetFile.getAbsolutePath() + separator
				+ relativePath + separator + childFilename;
		return curTargetFilename;
	}
}

 
具体的な応用:
ExecuteConvertFileTest.java
package com.landry.test;

import java.io.FileNotFoundException;
import java.io.IOException;

import com.landry.encoding.ExecuteConvertFile;
import com.landry.encoding.ExecuteConvertFileImpl;

public class ExecuteConvertFileTest
{
	public static void main (String[] args)
	{
		ExecuteConvertFile execute = new ExecuteConvertFileImpl();
		//   
		String inFilename = "D:\\tomcat6\\webapps\\";
		//         
		// String inFilename = "D:\\tomcat6\\webapps\\doc\\aio.html";
		String outFilename = "D:\\output";
		String encoding = "UTF-8";
		try
		{
			execute.executeConvertFile(inFilename, outFilename, encoding);
		}
		catch (FileNotFoundException e)
		{
			e.printStackTrace();
		}
		catch (IOException e)
		{
			e.printStackTrace();
		}
	}
	
}