java web绝对路径获取

      String path="/"+Thread.currentThread().getContextClassLoader().getResource("").getPath().substring(1);
        System.out.println(path);
        path = path.replace("WEB-INF/classes/", "images/");
        System.out.println(path);

/D:/green/tomcats/apache-tomcat-6.0.37/webapps/myWeb/WEB-INF/classes/
/D:/green/tomcats/apache-tomcat-6.0.37/webapps/myWeb/images/

 

public class FileUtil {
	/**
	 * 获取项目绝对路径
	 * 
	 * @return
	 */
	public static String getRootPath() {
		String classPath = FileUtil.class.getClassLoader().getResource("/").getPath();
		String rootPath = "";
		// windows下
		if ("\\".equals(File.separator)) {
			rootPath = classPath.substring(1, classPath.indexOf("/WEB-INF/classes"));
			rootPath = rootPath.replace("/", "\\");
		}
		// linux下
		if ("/".equals(File.separator)) {
			rootPath = classPath.substring(0, classPath.indexOf("/WEB-INF/classes"));
			rootPath = rootPath.replace("\\", "/");
		}
		return rootPath;
	}
}


 

猜你喜欢

转载自blog.csdn.net/loveme888/article/details/40584305