java获取项目地址或tomcat绝对地址

在java项目中获取文件的路径,不管是相对路径还是绝对路径,其本质都是通过绝对路径去寻找。

获取项目地址

request.getSession().getServletContext().getRealPath("/");

获取tomcat的webapps地址

System.getProperty("user.dir").replace("bin", "webapps");

获取项目的classpath地址

方法一:Thread.currentThread().getContextClassLoader().getResource("") 

方法二:this.getClass().getResource("/")

以上参考:http://blog.sina.com.cn/s/blog_49cc672f0100x7st.html

如下是我自定义的类,该类通过查找自身生成的.class文件所在的位置,通过截取字符获取路径。获取结果如:‘/D:/apache-tomcat-7.0.61/webapps/’

public class FileUtil {

	private static String path;
	/**
	 * 获取保存文件的路径
	 * 
	 * @return
	 */
	public static String getSaveFilePath() {
		path = FileUtil.class.getProtectionDomain().getCodeSource().getLocation().getPath().split("/WEB-INF")[0];
		path = path.substring(0, path.lastIndexOf("/") + 1);
		return path;
	}
}
原文地址:https://www.cnblogs.com/guxingzhe/p/4904387.html