也许下面的代码可以帮助你。
它将打印它找到的每个文件夹和每个文件。如果文件是 a *.java
,代码会输入它并打印与 java 方法匹配的所有内容。
此外,如果需要,更改确定什么是方法的 REGEX。该行是:
public static final String JAVA_METHOD_REGEX = "(public|protected|private|static|\\s) +[\\w\\<\\>\\[\\]]+\\s+(\\w+) *\\([^\\)]*\\)";
完整代码:
public class ReadFilesAndMethods {
public static void main(String[] args) throws Exception {
File folder = new File("C:/Workspace/MyProject/src");
listFiles(folder, "");
}
public static final String JAVA_FILE_REGEX = "^\\w+\\.java";
public static final String JAVA_METHOD_REGEX = "(public|protected|private|static|\\s) +[\\w\\<\\>\\[\\]]+\\s+(\\w+) *\\([^\\)]*\\)";
public static void listFiles(File folder, String prefix) throws Exception {
for (final File fileEntry : folder.listFiles()) {
if (fileEntry.isDirectory()) {
System.out.println(prefix + fileEntry.getName() + "/");
listFiles(fileEntry, prefix + "\t");
} else {
System.out.println(prefix + fileEntry.getName());
if (fileEntry.getName().matches(JAVA_FILE_REGEX)) {
readMethodsFromJavaFile(fileEntry.getAbsolutePath(), prefix + "\t");
}
}
}
}
public static void readMethodsFromJavaFile(String fileName, String prefix) throws Exception {
Scanner scanner = new Scanner(new File(fileName));
String text = scanner.useDelimiter("\\A").next();
scanner.close();
Pattern pattern = Pattern.compile(JAVA_METHOD_REGEX);
Matcher matcher = pattern.matcher(text);
while (matcher.find()) {
System.out.println(prefix+matcher.group(0));
}
}
}
输出:
main/
java/
utils/
UsefulStuff.java
public Long getSomething(Class<?> classe)
public Whatever load(String anything)
Start.java
static void main(String[] args)
entity/
system/
User.java
public long getId()
public void setId(long id)
...