作用
项目或者自己代码库,总有不一样的编码文件,导致看一些代码乱码,忍不了自己写了一个插件,可以将文件统一改为utf8编码,安装插件或直接跑代码使用,希望对大家有帮助
核心代码
public class FileConverterUTF8Util {
public static void main(String[] args) throws Exception {
// 输入需要转化的文件所在文件夹
Scanner sc = new Scanner(System.in);
String directoryPath = sc.nextLine();
List<FileHolder> fileHolder = getFileHolder(directoryPath);
System.out.println(directoryPath + "文件夹的文件总数: " + fileHolder.size());
for (FileHolder holder : fileHolder) {
String filePath = holder.getFileAbsolutePath();
File file = holder.getFile();
FileInputStream fileTest = new FileInputStream(file);
// 获取文件编码
Charset detect = CharsetDetector.detect(fileTest);
if (detect == null) {
continue;
}
FileInputStream fileInputStream = new FileInputStream(filePath);
InputStreamReader reader = new InputStreamReader(fileInputStream, detect);
BufferedReader bufferedReader = new BufferedReader(reader);
String line;
StringBuilder stringBuilder = new StringBuilder();
while ((line = bufferedReader.readLine()) != null) {
stringBuilder.append(line);
stringBuilder.append(System.getProperty("line.separator"));
}
bufferedReader.close();
PrintWriter printWriter = new PrintWriter(file, String.valueOf(StandardCharsets.UTF_8));
printWriter.println(stringBuilder);
printWriter.close();
}
}
/**
* 获得文件夹下所有文件
*
* @param filePath 文件夹绝对路径
* @return 文件集合
*/
public static List<FileHolder> getFileHolder(String filePath) {
File file = new File(filePath);
List<FileHolder> fileHolders = new ArrayList<>();
setFile(file, fileHolders);
return fileHolders;
}
/**
* 构建所有要转换编码的文件
* @param file 指定文件或者文件夹
* @param list 需要转换编码的文件集合
*/
private static void setFile(File file, List<FileHolder> list) {
if (file.isDirectory()) {
File[] files = file.listFiles();
if (files == null) {
return;
}
for (File file1 : files) {
if (file1.isDirectory()) {
setFile(file1, list);
} else {
if (file1.getName().endsWith(".java")) {
FileHolder fileHolder = new FileHolder();
fileHolder.setFileAbsolutePath(file1.getAbsolutePath());
fileHolder.setFile(file1);
list.add(fileHolder);
}
}
}
} else {
FileHolder fileHolder = new FileHolder();
fileHolder.setFile(file);
fileHolder.setFileAbsolutePath(file.getAbsolutePath());
list.add(fileHolder);
}
}
@Data
public static class FileHolder {
/**
* 文件绝对路径
*/
private String fileAbsolutePath;
/**
* 文件
*/
private File file;
}
}
插件包
https://gitee.com/SJYbean/converter-utf8