因为翻看以前的项目,有些使用的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);
}
}
}
}
}