如何获取JAR中包含的类路径中的目录中的文件列表?

时间:2017-06-11 16:49:24

标签: java classloader

如何获取JAR中包含的类路径中目录中的文件列表?

问题不在于按字面意思打开JAR文件并在其中的目录下查找文件。问题是具体如何列出恰好位于类路径中的目录中的文件,因为JAR包含在类路径中。所以不应该涉及开放的JAR文件。如果无法做到这一点,请在不事先知道罐子的文件名的情况下解释原因和方法。

假设项目依赖于另一个项目,其资源结构如下:

src/main/resources/testFolder
 - fileA.txt
 - fileB.txt

鉴于testFolder在类路径中可用,我如何枚举其下的文件?

testFolder最终位于JAR中,该JAR位于WAR的lib文件夹中,与依赖关系一样。

1 个答案:

答案 0 :(得分:0)

    PathMatchingResourcePatternResolver scanner = new PathMatchingResourcePatternResolver();
    Resource[] resources;
    try {
        resources = scanner.getResources("classpath*:testFolder/**/*.*");
        for (int i = 0; i < resources.length; i++) {
            log.info("resource: {}", resources[i].getFilename() );
        }
    } catch (IOException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }

在阅读底层实现后,我发现了以下内容:

URLConnection con = rootDirResource.getURL().openConnection();
JarFile jarFile;
String jarFileUrl;
String rootEntryPath;
boolean newJarFile = false;

if (con instanceof JarURLConnection) {
    // Should usually be the case for traditional JAR files.
    JarURLConnection jarCon = (JarURLConnection) con;
    ResourceUtils.useCachesIfNecessary(jarCon);
    jarFile = jarCon.getJarFile();
    jarFileUrl = jarCon.getJarFileURL().toExternalForm();
    JarEntry jarEntry = jarCon.getJarEntry();
    rootEntryPath = (jarEntry != null ? jarEntry.getName() : "");
}
else {
    // No JarURLConnection -> need to resort to URL file parsing.
    // We'll assume URLs of the format "jar:path!/entry", with the protocol
    // being arbitrary as long as following the entry format.
    // We'll also handle paths with and without leading "file:" prefix.
    String urlFile = rootDirResource.getURL().getFile();
    int separatorIndex = urlFile.indexOf(ResourceUtils.JAR_URL_SEPARATOR);
    if (separatorIndex != -1) {
        jarFileUrl = urlFile.substring(0, separatorIndex);
        rootEntryPath = urlFile.substring(separatorIndex + ResourceUtils.JAR_URL_SEPARATOR.length());
        jarFile = getJarFile(jarFileUrl);
    }
    else {
        jarFile = new JarFile(urlFile);
        jarFileUrl = urlFile;
        rootEntryPath = "";
    }
    newJarFile = true;
}

看看Spring的实现,似乎唯一的方法是将资源实际视为JAR文件。