Julka Cz
Julka Cz

Reputation: 65

SpringBoot - read file, path from application.properties

I'm writing a controller that will download text from a .txt file located in the 'temp' folder and display it on the page. I did this by a simple method using a Scanner-

   @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;
}

but the file path should be downloaded from the application.properties file. Anyone got an idea what should I use? I am using SpringBoot 1.5.3.

Upvotes: 3

Views: 5034

Answers (2)

Mahsun Fahmi
Mahsun Fahmi

Reputation: 1

Best solution:

above answer is good, but to create better code use file instead of String

    @Value("${key that placed in property file}")
    private File 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;
 }

Upvotes: 0

user7160972
user7160972

Reputation:

You can try this

        @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;
     }

Upvotes: 1

Related Questions