经过java类获取项目绝对路径两种方式

常常会遇到经过java类获取项目路径,而且经过该相对路径或者绝对路径加载资源文件的问题。一般最经常使用的的两种方式是经过classLoader或者class的getResource()方法。java

其实就是clsssLoader获取的路径是相对于classPath的,class获取的路径是相对于该类的。web

public static final String getPath(){
		String path1 = Constant.class.getClassLoader().getResource("").getPath();
		String path2 = Constant.class.getClassLoader().getResource("/").getPath();
		String path3 = Constant.class.getResource("").getPath();
		String path4 = Constant.class.getResource("/").getPath();
		System.out.println(path1);
		System.out.println(path2);
		System.out.println(path3);
		System.out.println(path4);
		return path1;
	}

经过该段代码的打印结果,能够判断path1,path2,path4都是获得项目的classPath路径,path3是获得类的classPath路径。spa

获取到项目的classPath路径,就能够操做项目的各类资源文件了,还能够在路径的上层路径添加文件夹或者文件。code

固然对于web项目有本身的方法,获取项目路径,以下资源

request.getSession().getServletContext().getRealPath("/xx");
相关文章
相关标签/搜索