当前位置:首页 > 开发 > 编程语言 > 编码 > 正文

文件编码格式转换

发表于: 2012-12-18   作者:ctrain   来源:转载   浏览:
摘要: 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;
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();
		}
	}
}

文件编码格式转换

  • 0

    开心

    开心

  • 0

    板砖

    板砖

  • 0

    感动

    感动

  • 0

    有用

    有用

  • 0

    疑问

    疑问

  • 0

    难过

    难过

  • 0

    无聊

    无聊

  • 0

    震惊

    震惊

版权所有 IT知识库 CopyRight © 2009-2015 IT知识库 IT610.com , All Rights Reserved. 京ICP备09083238号