[英]Eclipse API: Get IFile or fully-qualified name from IJavaProject using only the file's name string
Given only the name of a .java file (a String) and access to its IJavaProject
, how can I find the file's IFile or fully qualified path? 仅给出.java文件的名称(字符串)并访问其
IJavaProject
,如何找到文件的IFile或标准路径? For example, if the file name is Foo.java
, I have the String Foo
. 例如,如果文件名为
Foo.java
,则为String Foo
。
Here is my attempt, but it is too slow: 这是我的尝试,但是太慢了:
// Find the fully qualified path from "fileName".
for (ICompilationUnit unit : JDTUtility.getCompilationUnits(javaProject))
{
if (unit.getElementName().equals(fileName))
file = (IFile) unit.getResource();
}
// Get a list of ICompilationUnits from an IJavaProject object
public static List<ICompilationUnit> getCompilationUnits(IJavaProject javaProject)
{
ArrayList<ICompilationUnit> units = new ArrayList<>();
try
{
IPackageFragmentRoot[] packageFragmentRoots = javaProject.getAllPackageFragmentRoots();
for (int i = 0; i < packageFragmentRoots.length; i++)
{
IPackageFragmentRoot packageFragmentRoot = packageFragmentRoots[i];
IJavaElement[] fragments = packageFragmentRoot.getChildren();
for (int j = 0; j < fragments.length; j++)
{
IPackageFragment fragment = (IPackageFragment) fragments[j];
IJavaElement[] javaElements = fragment.getChildren();
for (int k = 0; k < javaElements.length; k++)
{
IJavaElement javaElement = javaElements[k];
if (javaElement.getElementType() == IJavaElement.COMPILATION_UNIT)
{
units.add((ICompilationUnit) javaElement);
}
}
}
}
}
catch (Exception e)
{
e.printStackTrace();
}
return units;
}
You can get the IProject
from the IJavaProject
using the getProject()
method: 您可以使用
getProject()
方法从IJavaProject
获取IProject
:
IProject project = javaProject.getProject();
The fastest way to scan the project is the accept(IResourceProxyVisitor)
method: 扫描项目的最快方法是
accept(IResourceProxyVisitor)
方法:
project.accept(new IResourceProxyVisitor()
{
@Override
public boolean visit(IResourceProxy proxy) throws CoreException
{
if ("Foo.java").equals(proxy.getName))
{
IPath workspacePath = proxy.requestFullPath();
// TODO deal with path
// Alternative
IResource resource = proxy.requestResource();
}
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.