[英]Why File path is not taking when i run as packaged 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>>>() {
});
而不是使用
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存档之外找到文件
另外,请记住,来自test目录的文件不会落入jar归档文件中,因此,仅在执行jar归档文件之前的测试执行期间, test目录中的这些文件和类才可用
从Spring Boot文档中
“ classpath:com / myapp / config.xml” =>从类路径加载
“ file:/data/config.xml” =>从文件系统作为URL加载
另外,您可以使用不带classpath:
和file:
前缀的ClassPathResource
例如,您有两个文件:
+-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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.