文件乱码,批量转换文件编码

因为翻看以前的项目,有些使用的GBK编码,现在一般都使用UTF8编码,所以自己写了个方法来递归转换编码。

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;

public class ConvertEncode {
    public static void main(String[] args) throws Exception {
        String path = "D:\\java_eclipse\\workspace\\Card\\src";
        convert(new File(path), new File("temp"), "GBK", "UTF8");
    }

    /**
     * 
     * @param f
     *            需要转换编码的文件或文件夹
     * @param savePath
     *            转码后的文件保存路径
     * @param fromEncode
     *            源文件编码
     * @param toEncode
     *            需要转换的编码
     * @throws Exception
     */
    public static void convert(File f, File savePath, String fromEncode, String toEncode) throws Exception {
        if (f.exists() && !f.isHidden()) {// 隐藏文件不转换
            if (f.isFile()) {
                InputStreamReader isr = new InputStreamReader(new FileInputStream(f), fromEncode);
                File newf = new File(savePath, f.getName());
                if (!newf.exists()) {
                    if (!newf.getParentFile().exists()) {
                        newf.getParentFile().mkdirs();
                    }
                    newf.createNewFile();
                }
                OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream(newf), toEncode);
                char[] buffer = new char[1024];
                int len = 0;
                while ((len = isr.read(buffer)) != -1) {
                    osw.write(buffer, 0, len);
                }
                osw.flush();
                osw.close();
                isr.close();
            } else if (f.isDirectory()) {
                // 递归转换文件夹下面的所有文件
                File[] files = f.listFiles();
                for (File file : files) {
                    convert(file, new File(savePath, f.getName()), fromEncode, toEncode);
                }
            }
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值