当我作为打包jar运行时,为什么文件路径没有占用?

时间:2018-10-15 18:30:10

标签: java spring-boot jar

我写了一行代码,用于在春季启动时在资源文件夹下获取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>>>() {
                    });

2 个答案:

答案 0 :(得分:0)

代替使用

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()

答案 1 :(得分:0)

看看Spring文档https://jsfiddle.net/8bz97a1u/2/

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

另外,请记住, test 目录中的文件不会落入jar存档中, test 目录中的这些文件和类仅在执行测试之前可用。建立jar存档

来自Spring Boot文档

  

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

     

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

另外,您可以使用Resource,不带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