SpringBoot - 从application.properties读取文件,路径
问题描述:
我正在编写一个控制器,它将从位于'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。
答
你可以试试这个
@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
无论如何,它已经很棒了 –
你从classpath加载它使用为ClassPathResource:https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/core /io/ClassPathResource.html – duffymo
你的意思是像一个'@Value(“$ {xyzfile}”)私有字符串文件名;'?换句话说,您可以使用@Value来访问已在application.properties中设置的属性。 –