Classpath资源在spring boot中无法解析

时间:2018-04-12 19:46:26

标签: spring spring-boot

我正在使用spring boot,我在资源文件夹中有一个文件。我正在使用数字海洋机器,当我使用java -jar mywebapp.war运行应用程序时,我无法从类路径访问该文件。我使用以下标准语法访问它:

File file = new ClassPathResource("mfile").getFile();

我收到的错误是类路径资源无法解析为绝对路径。我看到的问题是它正在显示路径!标记如下:

/home/u/webapp/target/mywebapp.war!/WEB-INF/classess!/mfile

我在这里做错了什么?

2 个答案:

答案 0 :(得分:0)

由于您使用java -jar运行它,因此应将其构建为JAR文件而不是WAR。

了解详情:https://docs.spring.io/spring-boot/docs/current/reference/html/deployment-install.html

答案 1 :(得分:0)

当以jar运行时,获取文件不起作用。您应该将其作为资源Stream获取。

ClassLoader classLoader = getClass().getClassLoader();
        InputStream inputStream = classLoader.getResourceAsStream("/file.xsd") ;
        File file = File.createTempFile("file", ".xsd");
        try {
            FileUtils.copyInputStreamToFile(inputStream, file);
        } finally {
            IOUtils.closeQuietly(inputStream);

它会为您提供一个文件。如果要求是作为文件获取。

相关问题