2017-07-14 98 views
1

我正在編寫一個控制器,它將從位於'temp'文件夾中的.txt文件下載文本並將其顯示在頁面上。 我用掃描器 -SpringBoot - 從application.properties讀取文件,路徑

@GetMapping("/file") 
    @ResponseBody 
    public String loadFile() throws FileNotFoundException { 
    String test; 
    Scanner br = new Scanner(new FileReader("/example/temp/temp.txt")); 

    StringBuilder sb = new StringBuilder(); 
    while (br.hasNext()) { 
     sb.append(br.next()); 
    } 
    br.close(); 
    test = sb.toString(); 

    return test; 
} 

但該文件應該從application.properties文件下載路徑不希望這一個簡單的方法。任何人都知道我應該使用什麼?我正在使用SpringBoot 1.5.3。

+0

你從classpath加載它使用爲ClassPathResource:https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/core /io/ClassPathResource.html – duffymo

+5

你的意思是像一個'@Value(「$ {xyzfile}」)私有字符串文件名;'?換句話說,您可以使用@Value來訪問已在application.properties中設置的屬性。 –

回答

0

你可以試試這個

 @Value("${key that placed in property file}") 
     private String file; 

     @GetMapping("/file") 
     @ResponseBody 
     public String loadFile() throws FileNotFoundException { 
     String test; 
     Scanner br = new Scanner(new FileReader(file)); 

     StringBuilder sb = new StringBuilder(); 
     while (br.hasNext()) { 
      sb.append(br.next()); 
     } 
     br.close(); 
     test = sb.toString(); 

     return test; 
    } 
+0

我已經在您回覆之前就像您一樣完成了這項工作;) 並且發生了一個例外: 「無法解析值爲」$ {path.temp.file}「的佔位符'path.temp.file'」 正在將「path.temp.file = /home/git/example/temp/temp.txt」添加到「application.properties」中,還是應該做一些不同的事情? –

+0

無論如何,它已經很棒了 –