起因:因下载了一些java源代码,存在大约五百个java项目源文件。使用IDEA加载java文件时,其中中文内容全部乱码,立马便想起我的IDEA是utf-8编码,可能这些源码是由GBK进行的字符编码,由于博主很懒,想要通过代码的方式进行转换编码成为我自己使用的UTF8编码,于是就有了这篇文章,可以直接拿来使用的java编码转换工具类。
调用方法:MyUtils.toCharset("文件路径", "GBK原本编码", "UTF-8更改编码");
java工具类文件代码:
import java.io.*;
public class MyUtils {
private MyUtils() {
}
//调用方法MyUtils.toCharset("文件路径", "GBK原本编码", "UTF-8更改编码");
//编码功能
public static void toCharset(String filename, String charset, String destCharset) {
//创建源文件地址
File src = new File(filename);
//源文件地址下创建转码后文件
File dest = new File(src + File.separator + "ToCharsetFile");
//创建转码文件地址
if (!dest.exists()) {
boolean mkdirs = dest.mkdirs();
}
searchFileEncode(src, charset, dest, destCharset);
}
private static void searchFileEncode(File src, String charset, File dest, String destCharset) {
/*try {
Thread.sleep(1000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}*/
File[] files = src.listFiles();
if (files != null) {
for (File file : files) {
if (file.isDirectory()) {
File destDir = null;
String path1 = file.getParentFile().getAbsolutePath();
path1 = path1.replace("\\", "/");
String path2 = file.getAbsolutePath();
path2 = path2.replace("\\", "/");
String[] fname = path2.split(path1);
for (String s : fname) {
if (!s.equals("")) {
s = s.substring(1);
destDir = new File(dest + File.separator + s);
}
}
if (destDir.getName().contains("ToCharsetFile")) {
return;
}
assert destDir != null;
if (!destDir.exists()) {
boolean b = destDir.mkdirs();
}
searchFileEncode(file, charset, destDir, destCharset);
} else if (file.isFile()) {
//root
String path1 = file.getParentFile().getAbsolutePath();
path1 = path1.replace("\\", "/");
//filePath
String path2 = file.getAbsolutePath();
path2 = path2.replace("\\", "/");
//fileName
String[] fname = path2.split(path1);
File javaFile = null;
for (String s : fname) {
if (!s.equals("")) {
javaFile = new File(dest, s);
}
}
try {
BufferedReader br = new BufferedReader(
new InputStreamReader(
new FileInputStream(file), charset
)
);
assert javaFile != null;
BufferedWriter pw = new BufferedWriter(
new OutputStreamWriter(
new FileOutputStream(javaFile), destCharset
)
);
String s;
while ((s = br.readLine()) != null) {
pw.write(s);
pw.newLine();
}
pw.flush();
pw.close();
br.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
}
}