繁体   English   中英

访问子项目Spring Boot中的资源

[英]Access resources in subproject Spring Boot

我有1个根项目和3个模块(api,模型,存储)。 这是项目结构:

**root**
--**api**
----src
------main
--------java
----------Application.java
--------resources
----------data.csv
----build.gradle
--**model**
----src
----build.gradle
--**storage**
----src
----build.gradle
build.gradle
settings.gradle

在我的Application.java中,我试图从资源中读取CSV文件:

    @SpringBootApplication
    @EnableAutoConfiguration
    @EnableJpaRepositories
    @EnableSolrRepositories
    public class MyApp{

        public static void main(String[] args) throws IOException {
            SpringApplication.run(MatMatchApp.class);
            ClassPathResource res = new ClassPathResource("classpath:data.csv");
            String path =res.getPath();
            File csv = new File(path);
            InputStream stream = new FileInputStream(csv);
        }
    }

但是我遇到一个例外:

Caused by: java.io.FileNotFoundException: data.csv (The system cannot find the file specified)
    at java.io.FileInputStream.open0(Native Method) ~[na:1.8.0_101]
    at java.io.FileInputStream.open(FileInputStream.java:195) ~[na:1.8.0_101]
    at java.io.FileInputStream.<init>(FileInputStream.java:138) ~[na:1.8.0_101]

我也在尝试以下代码:

File file = new File(getClass().getResource("data.csv").getFile());

有什么建议如何从API项目的资源中读取文件?

已解决此代码可以正常工作:

InputStream is = new ClassPathResource("/example.csv").getInputStream();

有关更多详细信息,请检查以下答案: 作为jar运行时找不到类路径资源

我测试了一个正常的项目,您可以在这里看到spring-boot-resource-access

您可能会在文件前错过/

ClassPathResource res = new ClassPathResource("classpath:/data.csv");

要么

File file = new File(getClass().getResource("/data.csv").getFile());

更新


测试您必须从实例类(例如ConfigurableApplicationContext找到ClassPath的应用程序

public static void main(String[] args) throws URISyntaxException {
    ConfigurableApplicationContext context = SpringApplication.run(DemoApplication.class);
    File csv = new File(context.getClass().getResource("/application.properties").toURI());
    System.out.println(csv.getAbsolutePath());
    System.out.println(String.format("does file exists? %s", csv.exists()));
}

这个答案帮助我解决了这个问题: 以jar运行时找不到类路径资源

resource.getFile()期望资源本身在文件系统上可用,即,不能嵌套在jar文件中。 您需要改用InputStream:

InputStream is = new ClassPathResource("/example.csv").getInputStream();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM