简体   繁体   English

从罐子中加载文件夹

[英]load a folder from a jar

I am trying to access a directory inside my jar file. 我正在尝试访问我的jar文件中的目录。 I want to go through every of the files inside the directory itself. 我想浏览目录本身内的每个文件。 I tried using the following: 我尝试使用以下内容:

File[] files = new File("ressources").listFiles();
        for (File file : files) {
            XMLParser parser = new XMLParser(file.getAbsolutePath());
            // some work
        } 

If I test this, it works well. 如果我对此进行测试,则效果很好。 But once I put the contents into the jar, it doesn't because of several reasons. 但是,一旦将内容物放入广口瓶中,并不是有几个原因。 If I use this code, the URL always points outside the jar. 如果使用此代码,则URL始终指向罐子外部。

structure of my project : 我的项目结构:

src 
   controllers
   models
         class that containt traitement
   views
ressources

See this: 看到这个:

How do I list the files inside a JAR file? 如何在JAR文件中列出文件?

Basically, you just use a ZipInputStream to find a list of files (a .jar is the same as a .zip) 基本上,您只是使用ZipInputStream查找文件列表(.jar与.zip相同)

Once you know the names of the files, you can use getClass().getResource(String path) to get the URL to the file. 一旦知道文件的名称,就可以使用getClass()。getResource(String path)获取文件的URL。

I presume this jar is on your classpath. 我认为这个jar在您的类路径中。

You can list all the files in a directory using the ClassLoader . 您可以使用ClassLoader列出目录中的所有文件。

First you can get a list of the file names then you can get URL s from the ClassLoader for individual files: 首先,您可以获取文件名列表,然后可以从ClassLoader获取单个文件的URL

public static void main(String[] args) throws Exception {
    final String base = "/path/to/folder/inside/jar";
    final List<URL> urls = new LinkedList<>();
    try (final Scanner s = new Scanner(MyClass.class.getResourceAsStream(base))) {
        while (s.hasNext()) {
            urls.add(MyClass.class.getResource(base + "/" + s.nextLine()));
        }
    }
    System.out.println(urls);
}

You can do whatever you want with the URL - either read and InputStream into memory or copy the InputStream into a File on your hard disc. 您可以使用URL进行任何操作-将InputStream读取并输入到内存中,或者将InputStream复制到硬盘上的File

Note that this definitely works with the URLClassLoader which is the default, if you are using an applet or a custom ClassLoader then this approach may not work. 请注意,这绝对适用于默认的URLClassLoader ,如果您使用的是applet或自定义的ClassLoader则此方法可能不起作用。

NB: 注意:

You have a typo - its resources not ressources . 您有错别字-它的resources不是ressources

You should use reverse domain name notation for your project, this is the convention. 您应该为项目使用反向域名表示法 ,这是约定。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM