Andrey E
Andrey E

Reputation: 866

Access resources in subproject Spring Boot

I have 1 root project and 3 modules(api,model,storage) in it. Here is the project structure:

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

In my Application.java I'm trying to read CSV file from the resources:

    @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);
        }
    }

But I'm getting an exception:

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]

I was trying the following code as well:

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

Any suggestions how can I read the file from resources in my API project?

SOLVED This code works fine:

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

For more details check this answer:Classpath resource not found when running as jar

Upvotes: 1

Views: 2952

Answers (2)

Andrey E
Andrey E

Reputation: 866

This answer helped me to solve the problem: Classpath resource not found when running as jar

resource.getFile() expects the resource itself to be available on the file system, i.e. it can't be nested inside a jar file. You need to use InputStream instead:

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

Upvotes: 1

Cavva79
Cavva79

Reputation: 399

I tested a normal project you can see here spring-boot-resource-access

You may miss that / in front of your file.

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

or

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

UPDATE


Testing the application you have to find ClassPath from an instanced class like ConfigurableApplicationContext for example

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

Upvotes: 2

Related Questions