【问题标题】:How to get files in directory of jar file in java?如何在java中获取jar文件目录中的文件?
【发布时间】:2015-05-12 12:27:31
【问题描述】:

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

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

第一个问题

并且在这个项目的resources/templates 目录中有一些特定的文件。并想要获取resources/templates 目录中的所有文件。

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

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

我在项目B 中称为myMethod,如下所示:

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

注意

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

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

【问题讨论】:

    标签: java maven resources directory classpath


    【解决方案1】:

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

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

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

    这里有一个链接可以帮助你:How do I list the files inside a JAR file?

    【讨论】:

      猜你喜欢
      • 2012-11-22
      • 2014-01-03
      • 2012-04-09
      • 2012-12-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-06-24
      • 1970-01-01
      相关资源
      最近更新 更多