java读取资源路径的几种实现方式
作者:worilb
文章总结了Java读取资源路径的几种方式,并指出了在JUnit测试文件和普通类中读取资源路径的区别,普通类中读取资源路径时,只返回主目录,而JUnit测试文件中可以精确到所在模块
java读取资源路径几种方式

@Test
public void path() throws IOException {
System.out.println("用户当前工作目录"+System.getProperty("user.dir"));
File directory = new File("");
String path2 = directory.getCanonicalPath();
System.out.println("当前工作目录1:"+path2);
String path3 = directory.getAbsolutePath();
System.out.println("当前工作目录2:"+path3);
String path = ClassUtils.getDefaultClassLoader().getResource("").getPath();
System.out.println("类加载器返回默认路径:"+path);
String path1 = ResourceUtils.getURL("classpath:").getPath();
System.out.println("ResourceUtils返回默认路径:"+path1);
String resourcePath = Thread.currentThread().getContextClassLoader().getResource("").getPath();
System.out.println("resourcePath返回默认路径:"+resourcePath);
ClassPathResource classPathResource = new ClassPathResource("excel/xx.xlsx");
System.out.println("ClassPathResource返回资源路径:"+classPathResource.getURL());
URL resource = this.getClass().getClassLoader().getResource("excel/xx.xlsx");
System.out.println("类加载器返回资源路径:"+resource.getPath());
URL url = ResourceUtil.getResource("excel/xx.xlsx");
System.out.println("ResourceUtil返回资源路径:"+url.getPath());
}

注意:
以上是在Junit测试文件中的结果
工作可以精确到所在模块,而普通类里打印是只有主目录没有模块的。
如下:
public static void main(String[] args) throws IOException {
System.out.println("用户当前工作目录"+System.getProperty("user.dir"));
File directory = new File("");
String path2 = directory.getCanonicalPath();
System.out.println("当前工作目录1:"+path2);
String path3 = directory.getAbsolutePath();
System.out.println("当前工作目录2:"+path3);
}
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。
