項目包含 100+ 插件需進行國際化改造,純手工修改工作量巨大。編寫自動化工具掃描 .java 文件,識別硬編碼中文字符串,自動插入 //$NON-NLS-n$ 標記供 Eclipse 國際化向導識別,大幅降低人工成本。
public static String readFile(String path) throws IOException {
File f = new File(path);
StringBuilder res = new StringBuilder();
try (FileInputStream fis = new FileInputStream(f);
InputStreamReader isr = new InputStreamReader(fis, Charset.forName("GBK"));
BufferedReader br = new BufferedReader(isr, 8192 * 8)) {
String line;
while ((line = br.readLine()) != null) {
res.append(line).append("\r\n");
}
}
return res.toString();
}
public static boolean writeFile(String content, String path) {
try (OutputStreamWriter writer = new OutputStreamWriter(
new FileOutputStream(path), "GBK")) {
writer.write(content);
return true;
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
private static final FileFilter JAVA_FILTER = pathname ->
pathname.isDirectory() || pathname.getName().toLowerCase().endsWith(".java");
public static void findFile(File f) throws IOException {
if (!f.exists()) return;
if (f.isDirectory()) {
for (File sub : f.listFiles(JAVA_FILTER)) {
findFile(sub);
}
} else {
updateFile(f);
}
}
private static void updateFile(File f) throws IOException {
StringBuilder res = new StringBuilder();
int modifiedLines = 0;
try (BufferedReader br = new BufferedReader(
new InputStreamReader(new FileInputStream(f), Charset.forName("GBK")), 8192 * 8)) {
String line;
while ((line = br.readLine()) != null) {
String updated = updateLine(line);
res.append(updated).append("\r\n");
if (!line.trim().equals(updated.trim())) modifiedLines++;
}
}
if (modifiedLines > 0) {
System.out.printf("文件修改: %s, 修改行數: %d%n", f.getPath(), modifiedLines);
writeFile(res.toString(), f.getPath());
}
}
private static String updateLine(String line) {
if (shouldSkip(line) || countChineseChars(line) == 0) return line;
int chineseCount = countChineseChars(line);
StringBuilder markers = new StringBuilder();
for (int i = 1; i <= chineseCount / 2; i++) {
markers.append(" //$NON-NLS-").append(i).append("$");
}
return line + markers;
}
// 過濾條件:import/package/class/註釋/註解/純英文/空行 等
private static boolean shouldSkip(String line) {
String trimmed = line.trim();
return trimmed.startsWith("import ")
|| trimmed.startsWith("package ")
|| trimmed.contains(" class ")
|| trimmed.contains("//$NON-NLS")
|| trimmed.startsWith("//")
|| trimmed.startsWith("/*")
|| trimmed.contains("*")
|| trimmed.startsWith("@")
|| !line.contains("\"")
|| trimmed.isEmpty()
|| containsChinese(trimmed); // 原邏輯似有誤,此處按意圖修正
}
private static boolean containsChinese(String str) {
return Pattern.compile("[\u4E00-\u9FA0]").matcher(str).find();
}
private static int countChineseChars(String str) {
Matcher m = Pattern.compile("[\u4E00-\u9FA0]").matcher(str);
int count = 0;
while (m.find()) count++;
return count;
}
BufferedReader(..., 64KB) 提升大文件讀取性能\u4E00-\u9FA0 覆蓋常用漢字.bakForkJoinPool 或線程池加速大項目掃描