2017-08-28 74 views
0

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

回答

0

这个答案HEL应用PED我要解决的问题: Classpath resource not found when running as jar

resource.getFile()预计,资源本身是可用的文件系统上,即它不能被嵌套在一个JAR文件中。您需要使用InputStream代替:

InputStream is = new ClassPathResource("/example.csv").getInputStream(); 
2

我测试了正常的项目,你可以在这里看到spring-boot-resource-access

您可能会错过/在你的文件前面。

ClassPathResource res = new ClassPathResource("classpath:/data.csv"); 

File file = new File(getClass().getResource("/data.csv").getFile()); 

UPDATE


测试,你必须从一个实例化类的ClassPath找到像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())); 
}