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

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

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

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路径。

获取到项目的classPath路径,就可以操作项目的各种资源文件了,还可以在路径的上层路径添加文件夹或者文件。

当然对于web项目有自己的方法,获取项目路径,如下

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


你可能感兴趣的:(通过java类获取项目绝对路径两种方式)