文件编码格式转换

package com.test;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;

/** 
 * 类描述: 批量转换文件编码格式 
 */
public class EncodeConverter {

	// 源文件编码  
	private static String srcEncode = "gbk";
	// 输出文件编码  
	private static String desEncode = "utf-8";

	
	/** 
	 * @param infile 源文件路径 
	 * @param outfile 输出文件路径 
	 * @param from 源文件编码 
	 * @param to 目标文件编码 
	 * @throws IOException 
	 * @throws UnsupportedEncodingException 
	 */
	public static void convert(String infile, String outfile, String from, String to) throws IOException, UnsupportedEncodingException {
		//BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(infile), from));
		//PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outfile), to)));
		InputStream ins = new FileInputStream(infile);
		OutputStream ous = new FileOutputStream(outfile);
		/*String reading;
		while ((reading = in.readLine()) != null) {
			out.println(reading);
		}*/
		byte[] b = new byte[(int)new File(infile).length()];
		while(ins.read(b, 0, b.length) != -1) {
			String tmp = new String(b,from);
			ous.write(tmp.getBytes(to));
		}
		ous.close();
		ins.close();
	}

	public static void main(String[] args) {
		if(!(args.length == 2)){
			System.out.println("[ 文件编码转换错误 ]====================参数个数不正确");
		}
		String infile = args[0];
		String outfile = args[1];	
		File file = new File(infile);
		if(!file.exists()) {
			System.out.println("[ 文件编码转换错误 ]====================" + file.getAbsolutePath()+" 不存在====================");
		}
		try {
			convert(infile, outfile, srcEncode, desEncode);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}

你可能感兴趣的:(编码格式)