今天列出几种获取真实路径的方法
一、web应用使用ServletContext
//通过HTTPServlet获取ServletContext
ServletContext servletContext = this.getServletContext();
//获取文件的服务器真实路径
//web目录下
String realPath = servletContext.getRealPath("/b.txt");
System.out.println(realPath);
二、springboot项目常用的两种获取classes真实路径方法
1.使用ClassUtils
String path = ClassUtils.getDefaultClassLoader()
.getResource("")
.getPath();
System.out.println(path);
2.使用ResourceUtils
try {
String path2 = ResourceUtils.getURL("classpath:").getPath();
System.out.println(path2);
} catch (FileNotFoundException e) {
e.printStackTrace();
}