1.通過ServletContext獲取
在tomcat5,6,7版本中我們可以通過ServletContext來獲取給定文件在服務器上的絕對路徑。
ServletContext context = getServletContext();
String path = context.getRealPath("文件在WebContent下的路徑");
這種方式能在tomcat5,6,7版本下獲取到文件在服務器上的絕對路徑,在tomcat8上則輸出為null。
2.tomcat8獲取文件在服務器上的絕對路徑
InputStream is = this.getClass().getClassLoader().getResourceAsStream("../../文件在WebContent下的路徑");
String path = this.getClass().getClassLoader().getResource("../../文件在WebContent下的路徑").getPath();