[英]Access resources in subproject Spring Boot
我有1個根項目和3個模塊(api,模型,存儲)。 這是項目結構:
**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();
有關更多詳細信息,請檢查以下答案: 作為jar運行時找不到類路徑資源
我測試了一個正常的項目,您可以在這里看到spring-boot-resource-access
您可能會在文件前錯過/
。
ClassPathResource res = new ClassPathResource("classpath:/data.csv");
要么
File file = new File(getClass().getResource("/data.csv").getFile());
更新
測試您必須從實例類(例如ConfigurableApplicationContext
找到ClassPath的應用程序
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()));
}
這個答案幫助我解決了這個問題: 以jar運行時找不到類路徑資源
resource.getFile()期望資源本身在文件系統上可用,即,不能嵌套在jar文件中。 您需要改用InputStream:
InputStream is = new ClassPathResource("/example.csv").getInputStream();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.