Friday, October 26, 2012

Get info in the project with eclipse/java

private static Set< ICompilationUnit> getFiles(String projname)
        throws CoreException {
    IWorkspaceRoot ws = ResourcesPlugin.getWorkspace().getRoot();
    IProject proj = ws.getProject(projname);
    IJavaProject javaProject = JavaCore.create(proj);
    Set< ICompilationUnit> files = new HashSet< ICompilationUnit>();
    javaProject.open(new NullProgressMonitor());
    for (IPackageFragment packFrag : javaProject.getPackageFragments()) {
        for (ICompilationUnit icu : packFrag.getCompilationUnits()) {
            files.add(icu);
        }
    }
    javaProject.close();
    return files;
}
ICompilationUnit file = …;
IResource resource = null;
try {
	resource = file.getUnderlyingResource();
} catch (JavaModelException e) {
    e.printStackTrace();
}
if (resource.getType() == IResource.FILE) {
    IFile ifile = (IFile) resource;
    String path = ifile.getRawLocation().toString();
}

What it does is get IWorkspaceRoot, and from it, you can get IJavaProject. Then, open with NullProgressMonitor(). For all of the PackageFragment, we can find ICompilationUnit, and add it to the files HashSet.

The issue is how to get the physical path from the compilation unit?
private String getWorkbenchDirectory() throws FileNotFoundException
{
	IPath path = Platform.getLocation();
	String filePath = path.toOSString();
	return filePath;
}

References

  1. Get the absolute path of the currently edited file in Eclipse
  2. How to get file path information from ICompilationUnit?
  3. How do I get the file path of the open workspace for developing plugins in eclipse

No comments:

Post a Comment