如何获取资源“文件夹"?从我的 jar 文件里面? [英] How can I get a resource "Folder" from inside my jar File?

查看:36
本文介绍了如何获取资源“文件夹"?从我的 jar 文件里面?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的项目根目录中有一个资源文件夹/包,我没有"想加载某个文件.如果我想加载某个文件,我会使用 class.getResourceAsStream ,我会没事的!!我真正想做的是加载一个文件夹".在资源文件夹中,在该文件夹内的文件上循环并获取每个文件的流并读取内容...假设在运行之前未确定文件名...我该怎么办?有没有办法在您的 jar 文件中获取文件夹内的文件列表?请注意,带有资源的 Jar 文件与运行代码的 jar 文件相同...

I have a resources folder/package in the root of my project, I "don't" want to load a certain File. If I wanted to load a certain File, I would use class.getResourceAsStream and I would be fine!! What I actually want to do is to load a "Folder" within the resources folder, loop on the Files inside that Folder and get a Stream to each file and read in the content... Assume that the File names are not determined before runtime... What should I do? Is there a way to get a list of the files inside a Folder in your jar File? Notice that the Jar file with the resources is the same jar file from which the code is being run...

推荐答案

终于找到了解决方案:

final String path = "sample/folder";
final File jarFile = new File(getClass().getProtectionDomain().getCodeSource().getLocation().getPath());

if(jarFile.isFile()) {  // Run with JAR file
    final JarFile jar = new JarFile(jarFile);
    final Enumeration<JarEntry> entries = jar.entries(); //gives ALL entries in jar
    while(entries.hasMoreElements()) {
        final String name = entries.nextElement().getName();
        if (name.startsWith(path + "/")) { //filter according to the path
            System.out.println(name);
        }
    }
    jar.close();
} else { // Run with IDE
    final URL url = Launcher.class.getResource("/" + path);
    if (url != null) {
        try {
            final File apps = new File(url.toURI());
            for (File app : apps.listFiles()) {
                System.out.println(app);
            }
        } catch (URISyntaxException ex) {
            // never happens
        }
    }
}

当您在 IDE 上运行应用程序时(不是使用 jar 文件),第二个块才起作用,如果您不喜欢,可以将其删除.

The second block just work when you run the application on IDE (not with jar file), You can remove it if you don't like that.

这篇关于如何获取资源“文件夹"?从我的 jar 文件里面?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆