import java.io.*;
import java.nio.file.Files;
import java.util.Arrays;
import java.util.List;
public class Main {
private static List<String> reencodingFileSuffix = Arrays.asList(
".java"
// ".sql",
// ".txt",
// ".config",
// ".conf",
// ".properties",
// ".xml",
// ".css",
// ".html",
// ".htm",
// ".jsp"
);
public static void main(String[] args) throws IOException {
//init
if (args.length == 0) {
throw new IllegalArgumentException("请输入项目完整路径");
}
String basePath = args[0];
String srcEncoding = "GBK";
String toEncoding = "UTF-8";
System.out.println("待转换项目路径:" + basePath);
System.out.println("转换后项目路径:" + basePath + "_reencoding");
if (args.length == 3) {
srcEncoding = args[1];
toEncoding = args[2];
}
System.out.println("项目由 " + srcEncoding + " 转换至 " + toEncoding);
// path check
File srcPathFile = new File(basePath);
if (!srcPathFile.exists() || !srcPathFile.isDirectory()) {
System.out.println("不存在的路径/不是目录,拒绝转换");
return;
}
File destPathFile = new File(srcPathFile.getAbsolutePath() + "_reencoding");
if (destPathFile.exists()) {
throw new IllegalStateException(destPathFile.getAbsolutePath() + "已经存在");
}
//reencoding
reencoding(srcPathFile, destPathFile, srcEncoding, toEncoding);
}
private static void reencoding(File baseSrcFolder, File baseDestFolder, String srcEncoding, String toEncoding) throws IOException {
if (!baseDestFolder.exists()) {
baseDestFolder.mkdir();
}
File[] srcFiles = baseSrcFolder.listFiles();
for (File srcFile : srcFiles) {
File destFilePath = new File(baseDestFolder.getAbsolutePath() + "/" + srcFile.getName());
if (srcFile.isDirectory()) {
reencoding(srcFile, destFilePath, srcEncoding, toEncoding);
} else {
int dotLastIndex = srcFile.getName().lastIndexOf('.');
String suffix = dotLastIndex == -1 ? null : srcFile.getName().substring(dotLastIndex);
if (dotLastIndex == -1 || !reencodingFileSuffix.contains(suffix)) {
Files.copy(srcFile.toPath(), destFilePath.toPath());
System.out.println("原样拷贝 " + srcFile.getAbsolutePath() + " 完成");
} else {
try (
BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(srcFile), srcEncoding));
PrintWriter out = new PrintWriter(destFilePath.getAbsolutePath(), toEncoding)
) {
String line = null;
while ((line = in.readLine()) != null) {
out.println(line);
}
System.out.println("拷贝并转换编码 " + srcFile.getAbsolutePath() + " 完成");
} catch (IOException e) {
throw e;
}
}
}
}
}
}
将以前的老代码,批量转换为UTF-8编码(可指定)
最新推荐文章于 2024-05-23 17:19:24 发布