Java项目中,如何获取项目中模板文件的绝对路径?(windows和linux下通用)

背景

今天写项目的时候,需要获取到在项目中的模板文件,那么如何获取呢?话不多说,贴代码

String templateRealPath = request.getSession().getServletContext().getRealPath("template")
                                        + File.separator + "report_template.xlsx";

模板文件位置
解释:

  1. request.getSession().getServletContext() 获取 Servlet 容器对象;
  2. getRealPath(“template”) 获取实际路径 , template 代表项目根目录;
  3. **File.separator():**问题来了,windows环境的路径分隔符是“\”,而Linux下的路径分隔符是“/”,但项目如果要跨平台使用,使用 “\” 或 “/” 就不合适了,所以这时就应该用java自带的File.separator代替,否则可能出现No Such file or diretory的异常。

Guess you like

Origin blog.csdn.net/manqishizhizhu/article/details/120857321