【问题标题】:How can I get the Url of file that is outside the jar?如何获取 jar 外部文件的 Url?
【发布时间】:2020-12-04 16:53:54
【问题描述】:

我已经使用 maven-assembly-plugin 以分解模式部署了 Spring Boot 应用程序。我已经从项目的资源文件夹中创建了配置文件夹。

问题是我无法获取 url 来访问配置文件夹中的文件。

如何获取我已上传并存储在此配置文件夹中的文件的 url。

文件结构

目标文件夹:

+springdemo-0.0.1-application.zip
   +config
     +myfolder
        -oldfile.png
   +springdemo-0.0.1.jar    //running this jar file
   +start.sh
-springdemo-0.0.1.jar   

我想要存储在 myfolder 中的文件的 URL。该 url 将被第 3 方(例如 Picasso)访问以获取文件数据。我无法获得指向此 myfolder 文件的正确 url。

【问题讨论】:

    标签: java spring spring-boot jar


    【解决方案1】:

    这很简单,您需要提供外部 application.properties 文件的完整路径,而不是在运行时启动 spring-boot.jar 应用程序期间源代码中存在的路径。

    示例:java -jar -Dspring.config.location=file://

    这个外部文件优先于我们的 jar 文件中的那个。

    【讨论】:

      【解决方案2】:

      注意:不是 SpringBoot 特定的答案,只是简单的 Java 方式。

      您只能尝试猜测文件的位置,因为在运行 Java 应用程序时无法知道工作目录。

      例如,如果您控制 Java 应用程序的执行方式,您可以尝试一种非常简单的方法:

      var configFile = new File("config/application.properties");
      

      只要进程从 start.sh 所在的同一目录启动(这似乎是您想要的),这将起作用。

      如果不起作用,请先尝试像这样打印工作目录:

      System.out.println("WRK DIR = " + new File(".").getAbsolutePath());
      

      这将告诉您文件的相对路径应该是什么。 因此,如果打印出 <root-dir>/springdemo 并且您知道您的配置文件在 <root-dir>/springdemo/mydir/config/ 下,那么文件路径应该是:

      new File("mydir/config/application.properties");
      

      顺便说一句,您可以使用以下命令轻松读取文件:

      // read file into List of lines
      Files.readAllLines(configFile);
      
      // specifically, for properties file
      var props = new Properties();
      props.load(new FileInputStream(configFile));
      

      如果出于某种原因您需要 URL 对象而不是文件,这很简单,只需调用:

      URL url = configFile.toURI().toURL()
      

      如果你想要配置目录下的所有文件,你可以先列出它们:

      File[] files = configFile.getParentFile().listFiles();
      if (files != null) {
          for (File file : files) {
              // use file?
          }
      }
      

      【讨论】:

      • new File(config/application.properties)FileNotFound Exception
      • 我认为您没有提供足够的信息。我以为你只是想知道如何找到一个文件并阅读它(这通常与 SpringBoot 无关)?或者您是否尝试使用某些 SpringBoot 特定功能?请查看我更新的答案,了解有关 Java 方式的更多详细信息。
      • 是的,我想知道如何找到一个文件,为此我应用了您的 Url url = configFile.toURI().toURL() 解决方案,但没有任何改变。
      • 我点击了这个链接:wimdeblauwe.com/blog/2014/…
      • 您发布的链接使用默认 SpringBoot 配置位置 config/application.properties,因此 Spring 无需您执行任何操作即可找到它。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-12-08
      • 2017-10-07
      • 2012-12-25
      • 2011-04-09
      • 2014-03-24
      • 2010-09-28
      相关资源
      最近更新 更多