Reputation: 65
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
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
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