依赖引入,pom.xml
<dependency>
<groupId>com.github.stuxuhai</groupId>
<artifactId>jpinyin</artifactId>
<version>1.1.8</version>
</dependency>
封装工具类 SimpleToTraditionalUtils
package com.iot.power.boot.utils;
import com.github.stuxuhai.jpinyin.ChineseHelper;
import org.apache.commons.collections.CollectionUtils;
import java.io.*;
import java.util.ArrayList;
import java.util.regex.Pattern;
/**
* Created by zhangzhenhua
*/
public class SimpleToTraditionalUtils {
public static void main(String[] args) {
SimpleChineseToTraditionalWithPath("F:\\testFile\\test");
}
public static void SimpleChineseToTraditionalWithPath(String path){
ArrayList<String> tempArray = new ArrayList<>();
ArrayList<String> fileList = traverseFolder2(path , tempArray);
if(CollectionUtils.isEmpty(fileList)){
return;
}
for (int i = 0; i<fileList.size() ; i++){
readFileAndReWriteInNewFile(fileList.get(i));
}
System.out.println("转换结束");
}
public static void readFileAndReWriteInNewFile(String filePath){
// 简体转繁体
try{
BufferedReader bufRead = new BufferedReader(new InputStreamReader(new FileInputStream(new File(filePath))));
StringBuilder strBuffer = new StringBuilder();
Pattern pattern = Pattern.compile("[\u4e00-\u9fcc]+");
for (String temp; (temp = bufRead.readLine())!= null; ){
if (pattern.matcher(temp).find()){
temp = convertToTraditionalChinese(temp);
}
strBuffer.append(temp);
strBuffer.append(System.getProperty("line.separator"));
}
//本地调试打印
System.out.println(strBuffer.toString());
bufRead.close();
PrintWriter printWriter = new PrintWriter(filePath);
printWriter.write(strBuffer.toString().toCharArray());
printWriter.flush();
printWriter.close();
}catch (IOException e){
e.printStackTrace();
}
}
/**
* 遍历传入的根文件夹,获取每一级文件夹的每个文件
* @param path 文件夹路径
* @param listFileName 返回文件路径的list
* @return
*/
public static ArrayList<String> traverseFolder2(String path , ArrayList<String> listFileName) {
File file = new File(path);
if (file.exists()) {
File[] files = file.listFiles();
if (files == null || files.length == 0) {
System.out.println("文件夹是空的!");
return null;
} else {
for (File file2 : files) {
if (file2.isDirectory()) {
traverseFolder2(file2.getAbsolutePath(),listFileName);
} else {
String solutePath = file2.getAbsolutePath();
//以下文件格式根据自己实际添加或删除
if (solutePath.endsWith(".jsp") || solutePath.endsWith(".js")
|| solutePath.endsWith(".html") || solutePath.endsWith(".java")
|| solutePath.endsWith(".properties") || solutePath.endsWith(".sql")
){
listFileName.add(file2.getAbsolutePath());
}
}
}
}
} else {
System.out.println("文件不存在!");
}
return listFileName;
}
/**
* 简体转换为繁体
* @param simpleStr 要转换的字符串
* @return
*/
public static String convertToTraditionalChinese(String simpleStr) {
String tempStr;
try {
tempStr = ChineseHelper.convertToTraditionalChinese(simpleStr);
} catch (Exception e) {
tempStr = simpleStr;
e.printStackTrace();
}
//本地验证系字转换有问题,单独处理
return tempStr.replace("係", "系");
}
}
写在结尾
本人实际项目中对.html、.js、.java、.sql、.properties转换基本没发现问题,自己仔细验证了项目转换为繁体后的页面显示和功能都正常,除了唯一看到“系”字转换错误。