I’m pretty new to Spring, so apologies if I don’t see the obvious answer here.
I set up small demo project with a Spring MVC controller and deployed it to App Engine. In my controller I would like to read the content of a static file into a String. What’s the best way of doing that?
I googled a bit but I’m probably searching for the wrong thing. I tried the below, but it does not work:
@Controller
@RequestMapping("/myController")
public class MyController {
@RequestMapping(value = "/test", method = RequestMethod.GET)
public @ResponseBody String myTest() {
FileReader fileReader = null;
BufferedReader bufferedReader = null;
String content = "";
try {
fileReader = new FileReader("file:/WEB-INF/content/somecontent.txt");
bufferedReader = new BufferedReader(fileReader);
content = bufferedReader.readLine();
bufferedReader.close();
}
catch (Exception ignored) {
// ignore
}
return content;
}
}
Any push into the right direction will be highly appreciated 🙂
The notation “file:” and “classpath:” isn’t right with FileReader.
I suggest you to create a FileSystemResource
and then to use getFile() or getInputStream() to read file.
This is very useful in a web application, because you can use relative path.