使用JDT ASTParser解析单个.java文件

首先,Eclipse JDT ASTParser可以在标准Java应用程序中工作。这剥夺了简单解析大量Java类文件的便利。假设您要解析目录下的100个.java文件。您将无法作为项目导入到Eclipse工作区。幸运的是,我们仍然可以使用ASTParser解析这些文件。
简而言之,有3个步骤可以做到:
1.从目录中读取文件名
2.从每个文件中获取代码字符串
3.使用JDT ASTParser进行解析
以下是运行程序所需的jar文件。这是前提条件,如果配置不正确,将会发生问题。
这是独立标准Java应用程序中ASTParser的完整代码。
import java.io.BufferedReader;import java.io.File;import java.io.FileReader;import java.io.IOException;import java.util.HashSet;import java.util.Set;
import org.eclipse.jdt.core.dom.AST;import org.eclipse.jdt.core.dom.ASTParser;import org.eclipse.jdt.core.dom.ASTVisitor;import org.eclipse.jdt.core.dom.CompilationUnit;import org.eclipse.jdt.core.dom.SimpleName;import org.eclipse.jdt.core.dom.VariableDeclarationFragment;
public class Main {

//use ASTParse to parse string
public static void parse(String str) {
	ASTParser parser = ASTParser.newParser(AST.JLS3);
	parser.setSource(str.toCharArray());
	parser.setKind(ASTParser.K_COMPILATION_UNIT);

	final CompilationUnit cu = (CompilationUnit) parser.createAST(null);

	cu.accept(new ASTVisitor() {

		Set names = new HashSet();

		public boolean visit(VariableDeclarationFragment node) {
			SimpleName name = node.getName();
			this.names.add(name.getIdentifier());
			System.out.println("Declaration of '" + name + "' at line"
					+ cu.getLineNumber(name.getStartPosition()));
			return false; // do not continue 
		}

		public boolean visit(SimpleName node) {
			if (this.names.contains(node.getIdentifier())) {
				System.out.println("Usage of '" + node + "' at line "
						+ cu.getLineNumber(node.getStartPosition()));
			}
			return true;
		}
	});

}

//read file content into a string
public static String readFileToString(String filePath) throws IOException {
	StringBuilder fileData = new StringBuilder(1000);
	BufferedReader reader = new BufferedReader(new FileReader(filePath));

	char[] buf = new char[10];
	int numRead = 0;
	while ((numRead = reader.read(buf)) != -1) {
		System.out.println(numRead);
		String readData = String.valueOf(buf, 0, numRead);
		fileData.append(readData);
		buf = new char[1024];
	}

	reader.close();

	return  fileData.toString();	
}

//loop directory to get file list
public static void ParseFilesInDir() throws IOException{
	File dirs = new File(".");
	String dirPath = dirs.getCanonicalPath() + File.separator+"src"+File.separator;

	File root = new File(dirPath);
	//System.out.println(rootDir.listFiles());
	File[] files = root.listFiles ( );
	String filePath = null;

	 for (File f : files ) {
		 filePath = f.getAbsolutePath();
		 if(f.isFile()){
			 parse(readFileToString(filePath));
		 }
	 }
}

public static void main(String[] args) throws IOException {
	ParseFilesInDir();
}}

最后,开发这么多年我也总结了一套学习Java的资料与面试题,如果你在技术上面想提升自己的话,可以关注我,私信发送领取资料或者在评论区留下自己的联系方式,有时间记得帮我点下转发让跟多的人看到哦。在这里插入图片描述

发布了252 篇原创文章 · 获赞 20 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/zhaozihao594/article/details/105028672
今日推荐