java web获取文件路径
在java web开发中,经常会需要读取当前web app下某个目录中的文件,而要读取文件的第一步,就是获取文件的路径。
在java web中,获取文件路径的接口是request.getServletContext().getRealPath()。下面通过一个例子来看看传入不同的参数会有什么不同的结果。
项目名为my_project,放在D盘下。添加一个TestController,代码如下:
@Controller @RequestMapping("/test") public class TestController { @RequestMapping("") @ResponseBody public Object test(HttpServletRequest request) { System.out.println(request.getServletContext().getRealPath("")); System.out.println(request.getServletContext().getRealPath("/")); System.out.println(request.getServletContext().getRealPath("/WEB-INF")); System.out.println(request.getServletContext().getRealPath("WEB-INF")); return null; } }
输出如下:
D:\my_project\src\main\webapp\ D:\my_project\src\main\webapp\ D:\my_project\src\main\webapp\WEB-INF D:\my_project\src\main\webapp\WEB-INF
这样我们就知道该如何使用request.getServletContext().getRealPath()来获取我们要的文件的路径了。
对于一些希望受保护的文件,我们会将它们放在WEB-INF目录下。比如我将test.json放在/WEB-INF/static/json目录下,那么在Controller中我就会这样获得test.json的路径:
String path = request.getServletContext().getRealPath("/WEB-INF/static/json/test.json");