2017-08-28 67 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())); 
} 
相關問題