Add code author, date information
In the recent project code verification of the company, it is required to add signature comments for code accountability. Due to various reasons such as coding habits and cooperative development, the author information of the old project code is confused, so I wrote a tool class, recursively query the java related files, add the author and date information, and add the code:
package com.util; import java.io.*; public class FileHeaderUtil { public static void add(String path, String authName,String date) { File dir = new File(path); File[] files = dir.listFiles(); for (File file : files) { try { if (file.isDirectory()) { add(file.getCanonicalPath(), authName,date); } else if (file.getName().endsWith(".java")) { BufferedReader br = new BufferedReader(new FileReader(file)); StringBuilder content = new StringBuilder(); String strLine; boolean flag = false; boolean nextFlag = true; while ((strLine = br.readLine()) != null) { if (nextFlag && (strLine.matches("^@.*") || strLine.matches("^public.*[{]"))) { content.append("/**\n" + " * Created by " + authName + " on "+date+"\n" + " */\n"); nextFlag = false; }else if (strLine.matches(".*\\*.*\\d{4}[-/]\\d+[-/]\\d+.*")) { flag = true; break; } content.append(strLine+"\n"); } if (flag) { continue; } BufferedWriter bw = new BufferedWriter(new FileWriter(file)); bw.write(content.toString()); bw.flush(); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } } }
The tool class itself has not added a signature. By the way, test the effect. The signature information template can be customized according to the code. The code ignores the java file with the existing signature (the condition contains the date). Run the test code. Parameters: project directory, author information, and date
package com.util; public class Test { public static void main(String[] args) { FileHeaderUtil.add("F:\\projects\\test","varCode","2019/4/30"); } }
Test effect, directly view the written tool class and test class: