I need to find a specific file present in eclipse project which is in classpath of project.
I have IProject
instance but Dont know how to get IFile
instance
The IProject
interface extends the IContainer
which has several findMember
methods. You get an IResource which can be casted down to IFile
after checking its' type using getType
. Go over those interfaces, they are properly documented.
I was facing the same problem and this is in short what i did:
IResource getResource(IProject project, String folderPath, String fileName) {
IJavaProject javaProject = JavaCore.create(project);
for (IPackageFragmentRoot root : javaProject.getAllPackageFragmentRoots()) {
IPackageFragment folderFragment = root.getPackageFragement(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;
}
}
// file not found in any source path
return null;
}
It looks pretty ugly and maybe there's a more direct approach. But it works.
If you need to use the classpath, you have to use IJavaProject
and the way fragments work prevents directly searching for the file path, because it will assume the "." (period) in a file name is a java package separator. So i guess you have to first get the right folder and then the file.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.