FileCodeUtil.java 1.66 KB
package com.sitech.util;

import java.io.*;

/**
 * Created with IntelliJ IDEA.
 * User: Administrator
 * Date: 14-1-23
 * Time: 下午2:18
 * To change this template use File | Settings | File Templates.
 */
public class FileCodeUtil {
    public static void batchGbk2Utf8(File path) {
        if (path.exists() && path.isDirectory()) {
            File[] files = path.listFiles();
            for (File file : files) {
                batchGbk2Utf8(file);
            }
        } else {
            System.out.println(path.getAbsolutePath());
            encode(path, "gbk", "utf-8");
        }
    }

    public static void encode(File file, String from, String to){
        BufferedReader br = null;
        Writer out = null;
        try {
            StringBuffer sb = new StringBuffer();
            String line;
            br = new BufferedReader(new InputStreamReader(new FileInputStream(file), from));
            while ((line = br.readLine()) != null) {
                sb.append(line + "\n");
            }

            out = new BufferedWriter(new OutputStreamWriter(
                    new FileOutputStream(file), to));
            out.write(sb.toString());
            out.flush();
        }catch (Exception e){
            System.err.println(file.getName());
            e.printStackTrace();
        }finally {
            try {
                br.close();
                out.close();
            } catch (IOException e) {
                e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
            }
        }
    }

    public static void main(String[] args){
        FileCodeUtil.batchGbk2Utf8(new File("E:\\tivoli"));
    }
}