Search code examples
windowsspring-bootdirectoryspring-annotations

Directory path in Resource vs String


How do I give the directory path for Resource in spring boot project on Windows? I get the proper path/format when I use it as string.

This is what I have in application.properties

input.file = C:\\Users\\termine\\dev\\sample2.csv

I used this class just to test the directory path it throws:

@Component
public class pathtesting {

    public static String prop;

    @Value("${input.file}")
    public void setProp(String prop) {
        this.prop= prop;
    }

    @PostConstruct
    public void init() {
        System.out.println("================== " + prop + "================== ");
    }
}

It throws the proper path I have in windows 10. Output of pathtesting:

================== C:\Users\termine\dev\sample2.csv================== 

But when I use it as Resource as follows:

    @Value("${input.file}")
    private Resource inputResource;

    .
    .
     @Bean
    public FlatFileItemReader<PE> reader() {
        FlatFileItemReader<PE> itemReader = new FlatFileItemReader<PE>();
        itemReader.setLineMapper(lineMapper());
        itemReader.setLinesToSkip(1);
        itemReader.setResource(inputResource);
        return itemReader;
    }

..it throws this error:


    at org.springframework.scheduling.concurrent.ReschedulingRunnable.run(ReschedulingRunnable.java:93)
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$201(ScheduledThreadPoolExecutor.java:180)
    at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:293)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at java.lang.Thread.run(Thread.java:748)
Caused by: java.lang.IllegalStateException: Input resource must exist (reader is in 'strict' mode): ServletContext resource [/C:/Users/termine/dev/sample2.csv]
    at org.springframework.batch.item.file.FlatFileItemReader.doOpen(FlatFileItemReader.java:251)
    at org.springframework.batch.item.support.AbstractItemCountingItemStreamItemReader.open(AbstractItemCountingItemStreamItemReader.java:146)
    ... 36 common frames omitted

I tried several possible ways with no luck.


Solution

  • Reference your resource as a file like this:

    @Value("file:${input.file}")
    private Resource inputResource;