类的全路径和编译后的路径
我们知道在一个项目里获取文件路径是获取编译后out目录下的文件的路径,而不是我们写在src目录下的
写一个方法来验证一下:
@Test public void classPath(){ //验证类的加载路径 -> 怎样读取到beans.xml文件的 File file = new File(this.getClass().getResource("/").getPath()); System.out.println(file); //E:\%e5%ad%a6%e4%b9%a0\ij%20workspace\recorder_spring\spring5\out\production\spring //可以看到并不是src目录下而是生成的out目录下的 System.out.println("this =>" + this); //this =>com.recorder.spring.test.SpringBeanTest@757942a1 System.out.println("this.getClass() =>" + this.getClass()); //this.getClass() =>class com.recorder.spring.test.SpringBeanTest System.out.println("this.getClass().getResource(\"/\") =>" + this.getClass().getResource("/")); //this.getClass().getResource("/") =>file:/E:/%e5%ad%a6%e4%b9%a0/ij%20workspace/recorder_spring/spring5/out/production/spring/ //这是一个是URL类型 -> file://代表是文件协议 就像http://代表是一种网络协议 System.out.println("this.getClass().getResource(\"/\").getPath() =>" + this.getClass().getResource("/").getPath()); //URL这个类的 getPath方法是获取 该url的 路径部分字符串 }
好像懂了一点

getResource(“/”)中 / 代表根路径,相当于编译后的项目的根路径
本文来自博客园,作者:紫英626,转载请注明原文链接:https://www.cnblogs.com/recorderM/p/16265069.html

浙公网安备 33010602011771号