访问子项目Spring Boot中的资源

时间:2017-08-28 19:19:50

标签: java spring spring-boot resources

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

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

有关详细信息,请查看以下答案:Classpath resource not found when running as jar

2 个答案:

答案 0 :(得分:2)

我在这里测试了一个正常的项目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()));
}

答案 1 :(得分:0)

这个答案帮助我解决了这个问题: Classpath resource not found when running as jar

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

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