JAVA获取路径的几种通用方法

一、Class.getResource(String path)

path不以’/'开头时,默认是从此类所在的包下取资源;
path  以’/'开头时,则是从ClassPath根下获取资源;

获取到的路径一般是这种格式:/E:/workspace/Test/bin/testpackage/

二、Class.getClassLoader().getResource(String path)

path不能以’/'开头时;
path是从ClassPath根下获取资源;

获取到的路径一般是这种格式:/E:/workspace/Test/bin/testpackage/

三、System.getProperty("user.dir")

获取当前工程的根目录

注:

1、Class.getResource(String path) 与 Class.getClassLoader().getResource(String path) 获取的路径是以“/”分割的unix风格的路径,在windows平台上直接使用可能会有错误,可以使用File类根据平台转换:

new File(GeneralConstant.class.getResource("/").getPath()).getPath();

2、Class.getResource(String path) 与 Class.getClassLoader().getResource(String path) 获取的路径是经过url编码的,如果遇到空格,中文等奇怪的路径(正常是不应该出现这种路径的),获取的path可能无法被正确解析,需要使用 path = URLDecoder.decode(path, "UTF-8")转义; 才能获取到正确的unix风格的路径。

猜你喜欢

转载自blog.csdn.net/wangpeng322/article/details/81502934
今日推荐