我有IJavaProject
,我需要在此项目的类路径上找到资源,即相当于getClassLoader().getResources()
(注意:此调用返回Enumeration<URL>
而不是URL
log4j.xml
1}})。
如何从Eclipse bundle / plug-in检查Java项目的类路径,例如查找包含{{1}}的所有类路径条目?
答案 0 :(得分:0)
使用getPackageFragmentRoots()
获取类路径中的条目等效项。对于每个根,您可以调用getNonJavaResources()
来获取该根下的非Java事物,并且可以递归地调用getChildren()
来获取子项(在java层次结构中)。最终那些间接遍历的孩子将是java源文件,您可以通过向他们发送getUnderlyingResource()
方法来确认。
以下是一些代码:
private Collection<String> keys( IJavaProject project, String[] bundleNames ) throws CoreException, IOException {
Set<String> keys = Sets.newLinkedHashSet();
for( String bundleName : bundleNames ) {
IPath path = new Path( toResourceName( bundleName ) );
boolean found = false;
IPackageFragmentRoot[] packageFragmentRoots = project.getPackageFragmentRoots();
for( IPackageFragmentRoot root : packageFragmentRoots ) {
found |= collectKeys( root, path, keys );
}
if( ! found ) {
throw new BundleNotFoundException( bundleName );
}
}
return keys;
}
private boolean collectKeys( IPackageFragmentRoot root, IPath path, Set<String> keys ) throws CoreException, IOException {
IPath fullPath = root.getPath().append( path );
System.out.println( "fullPath=" + fullPath );
IFile file = root.getJavaProject().getProject().getFile( fullPath.removeFirstSegments( 1 ) );
System.out.println( "file=" + fullPath );
if( ! file.exists() ) {
return false;
}
log.debug( "Loading " + file );
InputStream stream = file.getContents( true );
try {
Properties p = load( file.getFullPath().toString(), stream );
keys.addAll( keySet( p ) );
} finally {
stream.close();
}
return true;
}
protected String toResourceName( String bundleKey ) {
String path = bundleKey.replace( '.', '/' );
return path + ".properties";
}