Java 访问子项目Spring Boot中的资源
我有1个根项目和3个模块(api、模型、存储)。 以下是项目结构:Java 访问子项目Spring Boot中的资源,java,spring,spring-boot,resources,Java,Spring,Spring Boot,Resources,我有1个根项目和3个模块(api、模型、存储)。 以下是项目结构: **root** --**api** ----src ------main --------java ----------Application.java --------resources ----------data.csv ----build.gradle --**model** ----src ----build.gradle --**storage** ----src ----build.gradle build.gr
**root**
--**api**
----src
------main
--------java
----------Application.java
--------resources
----------data.csv
----build.gradle
--**model**
----src
----build.gradle
--**storage**
----src
----build.gradle
build.gradle
settings.gradle
在my 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]
对如何从API项目的资源中读取该文件有何建议
已解决
此代码工作正常:
InputStream is = new ClassPathResource("/example.csv").getInputStream();
InputStream is = new ClassPathResource("/example.csv").getInputStream();
有关更多详细信息,请查看此答案:我测试了一个正常的项目,您可以在这里看到 您可能会错过文件前面的
/
ClassPathResource res = new ClassPathResource("classpath:/data.csv");
或
更新
测试应用程序时,必须从实例类(例如
ConfigurableApplicationContext
)中查找类路径
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()));
}
我测试了一个正常的项目,你可以在这里看到 您可能会错过文件前面的
/
ClassPathResource res = new ClassPathResource("classpath:/data.csv");
或
更新
测试应用程序时,必须从实例类(例如
ConfigurableApplicationContext
)中查找类路径
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()));
}
这个答案帮助我解决了这个问题: getFile()希望资源本身在文件系统上可用,即它不能嵌套在jar文件中。 您需要改用InputStream:
这个答案帮助我解决了这个问题: getFile()希望资源本身在文件系统上可用,即它不能嵌套在jar文件中。 您需要改用InputStream: