如何在java中获取jar文件目录中的文件?

时间:2023-01-27 11:16:50

assume that i have this code in a project A:

假设我在项目A中有这个代码:

public class test {
    public void myMethod() {
          String directoryPath = classLoader.getResource("") + "/templates/code/";
          // code to read directory files
    }
}

First Problem

and have some specific files in resources/templates directory of this project. and want to get all of the files that in the resources/templates directory.

并在此项目的资源/模板目录中有一些特定的文件。并希望获取resources / templates目录中的所有文件。

I'm added that project as a dependency to another project named B and want to call myMethod.

我将该项目添加为另一个名为B的项目的依赖项,并希望调用myMethod。

now, the myMethod works fine when calling in project A, but when i'm call it in B project it throws FileNotFoundException.

现在,myMethod在调用项目A时工作正常,但是当我在B项目中调用它时,它会抛出FileNotFoundException。

I'm call the myMethod in project B as you seen below:

我在项目B中调用myMethod,如下所示:

public class myClass {
    public static void main(String[] args) {
           myMethod();
    }
}

NOTE

1- Both of that projects is Spring, Maven project

1-这两个项目都是Spring,Maven项目

2- When i build project B, the jar file of project A is in WEB-INF/lib directory of B.

2-当我构建项目B时,项目A的jar文件位于B的WEB-INF / lib目录中。

1 个解决方案

#1


First you could use getResource to work with files as follow :

首先,您可以使用getResource来处理文件,如下所示:

    URL directoryPath = classLoader.getResource("resources/templates");
    File f = new File(directoryPath.getFile());

BUT, once your application is deployed as a jar, you can't access the ressources with "File" anymore. You need to read the content of the jar file.

但是,一旦您的应用程序部署为jar,您就无法再使用“File”访问资源。您需要阅读jar文件的内容。

Here's a link to help you : How do I list the files inside a JAR file?

这是一个帮助您的链接:如何列出JAR文件中的文件?

#1


First you could use getResource to work with files as follow :

首先,您可以使用getResource来处理文件,如下所示:

    URL directoryPath = classLoader.getResource("resources/templates");
    File f = new File(directoryPath.getFile());

BUT, once your application is deployed as a jar, you can't access the ressources with "File" anymore. You need to read the content of the jar file.

但是,一旦您的应用程序部署为jar,您就无法再使用“File”访问资源。您需要阅读jar文件的内容。

Here's a link to help you : How do I list the files inside a JAR file?

这是一个帮助您的链接:如何列出JAR文件中的文件?