java 文件編碼轉換

package com.folkSeal.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.Charset;

/** IO 工具類 */
public class IOCVUtils {
	/** 源文件編碼 */
	public static String sourceEncoding = "GBK";
	/** 目標編碼 */
	public static String targetEncoding = "UTF-8";

	/**
	 * 文件內容轉編碼
	 * @param sourceFile
	 * @param targetFile
	 * @throws UnsupportedEncodingException
	 * @throws FileNotFoundException
	 * @throws IOException
	 */
	public static void changeEncoding(File sourceFile, File targetFile)
			throws UnsupportedEncodingException, FileNotFoundException,
			IOException {
		FileInputStream fin = null;
		FileOutputStream fout = null;
		FileChannel fcin = null;
		FileChannel fcout = null;
		if (sourceEncoding == null) {
			IOCVUtils.sourceEncoding = System.getProperty("file.encoding");
		}
		try {
			fin = new FileInputStream(sourceFile);
			fout = new FileOutputStream(targetFile);
			fcin = fin.getChannel();
			fcout = fout.getChannel();
			ByteBuffer buffer = ByteBuffer.allocateDirect(1024);
			while (true) {
				buffer.clear();
				int r = fcin.read(buffer);
				if (r == -1) {
					break;
				}
				buffer.flip();
				fcout.write(ByteBuffer.wrap(Charset.forName(sourceEncoding).decode(buffer).toString().getBytes(targetEncoding)));
			}
		} finally {
			if (fin != null) {
				fin.close();
				fin = null;
			}
			if (fcin != null) {
				fcin.close();
				fcin = null;
			}
			if (fout != null) {
				fout.close();
				fout = null;
			}
			if (fcout != null) {
				fcout.close();
				fcout = null;
			}
		}
	}

	/**
	 * 文件內容轉編碼
	 * @param sourceFile
	 * @param targetFile
	 * @throws UnsupportedEncodingException
	 * @throws FileNotFoundException
	 * @throws IOException
	 */
	public static void changeEncoding(String sourceFile, String targetFile) throws UnsupportedEncodingException, FileNotFoundException, IOException{
		File fl1 = new File(sourceFile);
		File fo1 = new File(targetFile);
		changeEncoding(fl1, fo1);
	}

	/**
	 * 文件內容轉編碼
	 * @param sourceFile
	 * @param targetFile
	 * @param sourceEncoding 源文件編碼 默認源文件的系統存儲編碼 System.getProperty("file.encoding");
	 * @param targetEncoding 目標編碼 默認utf-8
	 * @throws UnsupportedEncodingException
	 * @throws FileNotFoundException
	 * @throws IOException
	 */
	public static void changeEncoding(String sourceFile, String targetFile,
			String sourceEncoding, String targetEncoding) throws UnsupportedEncodingException, FileNotFoundException, IOException {
		IOCVUtils.sourceEncoding = sourceEncoding;
		IOCVUtils.targetEncoding = targetEncoding;
		changeEncoding(sourceFile, targetFile);
	}
}


或者

package com.folkSeal.test;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

public class StreamGobbler extends Thread {   
	  
    InputStream is;   
    String type;   
  
    StreamGobbler(InputStream is, String type) {   
        this.is = is;   
        this.type = type;   
    }   
  
    public void run() {   
        try {   
            InputStreamReader isr = new InputStreamReader(is);   
            BufferedReader br = new BufferedReader(isr);   
            String line = null;   
            while ((line = br.readLine()) != null)   
                System.out.println(type + ">" + line);   
        } catch (IOException ioe) {   
            ioe.printStackTrace();   
        }   
    }   
}  


 

package com.folkSeal.test;

import java.io.File;

/**
 * 用於文件夾下的java文件的編碼自動轉換,如gbk轉utf-8
 * 
 * @author Wen Fuqiang
 * @company Fayhong Technology Co., Ltd.
 * @date 2010-1-26
 */
public class EncodingConverter {

	/**
	 * main方法入口
	 * 
	 * @param args
	 *            args[0] 給定需要轉換的文件夾 args[1] 指定需要轉換的編碼,如utf-8等
	 */
	public static void main(String[] args) {
		// if (args.length<2){
		// System.out.println("please input path of folder and encoding name");
		// System.exit(1);
		// }
		// else{
		// ec.convertEncode(args[0], args[1]);
		// }

		EncodingConverter ec = new EncodingConverter();

		// 暫時用src_path替換args[0],encoding_name替換arg[1]
		String src_path = "E:\\Workspaces\\folkSeal\\WebRoot\\file\\seal_templet_file\\xml\\2\\2\\";
		String encoding_name = "utf-8";
		ec.convertEncode(src_path, encoding_name);

	}

	public void convertEncode(String sourceFloder, String encoding_name) {
		File file = new File(sourceFloder);
		String[] files = file.list();

		for (String s : files) {
			if (s.indexOf('.') == -1) { // 表明這是個子目錄,迴歸調用此函數
				convertEncode(file.getAbsolutePath() + "\\" + s, encoding_name);
			} else {
				if (s.endsWith("xml")) { // 只處理以Java結尾的文件
					doConvertEncode(file.getAbsolutePath() + "\\" + s, file.getAbsolutePath()+ "\\" + s, encoding_name);
				}
			}
		}
	}

	/**
	 * 完成具體的編碼轉換工作
	 * 
	 * @param inputFile
	 *            輸入文件
	 * @param outputFile
	 *            輸出文件
	 * @param encoding_name
	 *            需要轉成的編碼格式
	 */
	public void doConvertEncode(String inputFile, String outputFile,
			String encoding_name) {
		Runtime rt = Runtime.getRuntime();
		String cmd[] = { "native2ascii.exe", "-reverse", "-encoding",
				encoding_name, inputFile, outputFile };
		System.out.println("Execing convert command for " + inputFile + " ...");

		try {
			Process proc = rt.exec(cmd);

			// any error message?
			StreamGobbler errorGobbler = new StreamGobbler(proc.getErrorStream(), "ERROR");

			// any output?
			StreamGobbler outputGobbler = new StreamGobbler(proc.getInputStream(), "OUTPUT");

			// kick them off
			errorGobbler.start();
			outputGobbler.start();

			// any error???
			int exitVal = proc.waitFor();
			System.out.println("ExitValue: " + exitVal);

		} catch (Throwable e) {
			e.printStackTrace();
		}
	}
}


 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章