我正在写一个eclipse-plugin,它可以访问当前在eclipse中打开的项目。在这些项目中,我需要访问源文件,不幸的是,源文件也可能位于与项目工作目录不同的位置。
考虑从现有资源创建一个新项目:
新项目位于文件夹C:/Users/username/runtime-EclipseApplication/JabRef
中,而源文件位于C:/Users/username/Downloads/git/jabref/
文件夹中
这将在.project-File中创建以下条目:
...
<linkedResources>
...
<link>
<name>java</name>
<type>2</type>
<location>C:/Users/username/Downloads/git/jabref/src/main/java</location>
</link>
</linkedResources>
...
和.classpath-File:
<?xml version="1.0" encoding="UTF-8"?>
<classpath>
<classpathentry kind="src" output="classes" path="java"/>
<classpathentry kind="src" output="classes" path="gen"/>
<classpathentry kind="var" path="JRE_LIB" rootpath="JRE_SRCROOT" sourcepath="JRE_SRC"/>
...
现在,我当前的代码给了我一个类似这样的filePath:net/sf/jabref/imports/MsBibImporter.java
(它是我通过bug.getPrimarySourceLineAnnotation().getSourcePath()
从FindBugs BugInstance获得的)。
我的目标是使用if(new RepositoryBuilder().findGitDir(new File(filePath)).getGitDir() != null)
为文件找到相应的git目录
我的所有方法都为我提供了项目目录中的路径,比如"C:/Users/username/runtime-EclipseApplication/JabRef/JabRef/java“,这些路径在物理上并不存在。
我可以通过IProject project
访问该项目。
发布于 2014-11-13 23:21:55
我使用以下三行代码使其正常工作
IPath path = project.getFile(bug.getPrimarySourceLineAnnotation().getSourcePath()).getProjectRelativePath();
IResource res = getResource(project, path.removeLastSegments(1).toString(), path.lastSegment());
File file = res.getLocation().toFile();
和一种来自https://stackoverflow.com/a/7727264/455578的方法
IResource getResource(IProject project, String folderPath, String fileName) {
IJavaProject javaProject = JavaCore.create(project);
try {
for (IPackageFragmentRoot root : javaProject.getAllPackageFragmentRoots()) {
IPackageFragment folderFragment = root.getPackageFragment(folderPath);
IResource folder = folderFragment.getResource();
if (folder == null || ! folder.exists() || !(folder instanceof IContainer)) {
continue;
}
IResource resource = ((IContainer) folder).findMember(fileName);
if (resource.exists()) {
return resource;
}
}
} catch (JavaModelException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// file not found in any source path
return null;
}
https://stackoverflow.com/questions/26909485
复制相似问题