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

标签 java classloader

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

问题不在于从字面上打开 JAR 文件并在其中的目录下查找文件。具体问题是如何列出恰好位于类路径中的目录中的文件,因为 JAR 包含在类路径中。所以不应该涉及打开 JAR 文件。如果这是不可能的,请解释为什么以及如何在事先不知道 jar 的文件名的情况下完成它。

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

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

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

testFolder 最终位于 JAR 内,该 JAR 位于 WAR 的 lib 文件夹内,而依赖项应位于该文件夹内。

最佳答案

    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 文件。

关于java - 如何获取 JAR 中包含的类路径中的目录中的文件列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44486325/

相关文章:

java - 如何在 pom.xml 中定义特定的 jar 以部署到 TOMCAT/lib 文件夹?

java - 如何使使用成熟的 m/w 类编写的遗留应用程序软件适应于在相同 m/w 类的子集上工作

java - 为什么 Android 类加载器允许从另一个包反射访问包私有(private)类的公共(public)字段?

java - 使用自定义类加载器加载 Java 运行时和 API 类

java - 如何修复 SwipeRefreshLayout 抖动?

java - JCombobox 为每个项目添加不同的颜色

tomcat - 如何使用无效的 ssl 证书通过 exchange 2007 SMTP 中继从 tomcat web 应用程序发送电子邮件?

jakarta-ee - 来自 IBM WebSphere Application Server 上的 WebJars 的静态资源不可见

java - 无法在某部手机上安装 apk

java - 使用 Selenium Webdriver(使用 Java)测试没有 ID 的视频