资源与字符串中的目录路径

Directory path in Resource vs String

如何在 Windows 上的 spring 引导项目中给出资源的目录路径? 当我将它用作字符串时,我得到了正确的 path/format。

这是我在 application.properties

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

我用这个 class 只是为了测试它抛出的目录路径:

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

它抛出了我在 windows 中的正确路径 10. 路径测试的输出:

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

但是当我将它用作资源时如下:

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

..它抛出这个错误:


    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.access1(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

我尝试了几种可能的方法,但没有成功。

像这样将您的资源引用为文件:

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