我有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