为什么当我作为打包的 jar 运行时文件路径不占用?



我写了一行用于在 Spring 启动的资源文件夹下获取 json 文件。当我通过 eclipse IDE 运行时,路径是正确的,但是当构建它并作为 jar 文件运行时,路径不正确。

private static Map<String, Map<String, String>> configs;
configs = mapper.readValue(
new File(System.getProperty("user.dir") + File.separator + "src" + File.separator + "main"
+ File.separator + "resources" + File.separator + "test" + File.separator + "text.json"),
new TypeReference<Map<String, Map<String, String>>>() {
});

而不是使用

new File(System.getProperty("user.dir") + File.separator + "src" + File.separator + "main" + File.separator + "resources" + File.separator + "test" + File.separator + "text.json")

尝试使用Spring Core提供的此功能。

new ClassPathResource("test/text.json").getFile()

看看 Spring 文档资源

此外,当您从 IDE 启动应用程序时,您的应用程序不会存档到 jar,因此您可以简单地通过路径访问文件,但是当您从 JAR 存档启动应用程序时java -jar my.jar您应该在类路径中搜索您的文件,但您也可以在启动的jar存档之外找到文件

另外,请记住,测试目录中的文件不属于 JAR 存档,测试目录中的这些文件和类仅在构建 JAR 存档之前的测试执行期间可用

来自 Spring 引导文档

"classpath:com/myapp/config.xml" => 从类路径加载

"file:/data/config.xml" => 作为 URL 从文件系统加载

此外,您可以使用不带classpath:file:前缀的类路径资源

例如,您有两个文件:

+-src
|  +-main
|  |  +-java
|  |  |  +-com
|  |  |  |  +-example
|  |  |  |  |  +-app
|  |  |  |  |  |  +-MyApp.java 
|  |  +-resources
|  |  |  +-foo.json
|  |  |  +-my-folder
|  |  |  |  +-bar.json

使用ClassPathResource时,您将在从 IDE 运行时和从jar存档中找到文件

@SpringBootApplication
public class MyApp {
public static void main(String[] args) {
SpringApplication.run(MyApp, args);
ClassPathResource fooClassPathResource = new ClassPathResource("foo.json");
System.out.println(fooClassPathResource.exists());
ClassPathResource barClassPathResource = new ClassPathResource("my-folder/bar.json");
System.out.println(barClassPathResource.exists());
}

}

控制台输出:

true   
true

相关内容

最新更新