2017-07-14 7 views
1

私は 'temp'フォルダにある.txtファイルからテキストをダウンロードしてページに表示するコントローラを作成しています。 私はapplication.propertiesファイルからダウンロードする必要がありますScanner-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; 
} 

が、ファイル・パスを使用して簡単な方法でこれをしませんでした。誰が私は何を使うべきか考えましたか?私はSpringBoot 1.5.3を使用しています。

+0

を試すことができます。https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/core /io/ClassPathResource.html – duffymo

+5

あなたは '@Value(" $ {xyzfile} ")プライベートStringファイル名のような意味ですか?つまり、@ Valueを使用して、application.propertiesに設定されているプロパティにアクセスすることができます。 –

答えて

0

あなたがClassPathResourceを使用して、クラスパスからそれをロードする必要があり、この

 @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

問題はありません。 –

関連する問題