我有1個root項目和3個模塊(api,model,storage)。 下面是項目結構:子項目中的訪問資源Spring Boot
**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