2012-11-16 40 views

回答

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"; 
} 
+0

能否请您检阅我的代码示例? –

+0

如果您要查找的文件位于文件系统上,它看起来会起作用。如果它在classpath中的jar中,我不知道你会以这种方式找到它。您可能必须在片段根目录上使用getNonJavaResources()。 –

+0

啊,是的。当我来到它时,我会更新代码以使用JARs(它们会返回'IStorage'而不是'IFile')。 –

相关问题