專案包含大量檔案,需刪除格式固定的無效註解:
/*無效資源開始
System.out.println("無效的內容");
無效資源結束*/
Files.walk(Paths.get(root)).filter(Files::isRegularFile)。String content = Files.readString(path); (Java 11+)。Pattern.DOTALL 跨行匹配:
String regex = "/\\*無效資源開始[\\s\\S]*?無效資源結束\\*/";
String cleaned = content.replaceAll(regex, "");
Files.writeString(path, cleaned);。StandardCharsets.UTF_8 避免中文亂碼。public static void cleanProject(Path root) throws IOException {
Pattern p = Pattern.compile("/\\*無效資源開始[\\s\\S]*?無效資源結束\\*/");
Files.walk(root)
.filter(Files::isRegularFile)
.filter(path -> path.toString().endsWith(".java"))
.forEach(path -> {
try {
String txt = Files.readString(path);
String newTxt = p.matcher(txt).replaceAll("");
if (!txt.equals(newTxt)) Files.writeString(path, newTxt);
} catch (IOException e) { e.printStackTrace(); }
});
}
[\\s\\S]*? 非貪婪匹配任意字元 (含換行),確保不跨越多個註解塊。*/,需升級為狀態機解析器,正則將失效。