gpt4 book ai didi

java - Eclipse API : Get IFile or fully-qualified name from IJavaProject using only the file's name string

转载 作者:行者123 更新时间:2023-12-01 13:17:42 27 4
gpt4 key购买 nike

仅给出 .java 文件的名称(字符串)和对其 IJavaProject 的访问权限,如何找到文件的 IFile 或完全限定路径?例如,如果文件名是 Foo.java,则我有字符串 Foo

这是我的尝试,但速度太慢:

// 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;
}

最佳答案

您可以使用 getProject() 方法从 IJavaProject 获取 IProject:

IProject project = javaProject.getProject();

扫描项目的最快方法是 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();
}
}
});

关于java - Eclipse API : Get IFile or fully-qualified name from IJavaProject using only the file's name string,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22336659/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com