为了编写的代码在其他系统中也能正常运行,因此需要这种方法,而不是直接复制粘贴一个绝对路径,如果直接复制粘贴的话那在windows中可以使用,但是换到其他系统中就不行了。
文件必须在src中,比如“helloword.txt”,
代码如下:
String path = Thread.currentThread().getContextClassLoader().getResource("ReflectPackage/helloworld.txt").getPath();
System.out.println(path);
代码中的“ReflectPackage/helloworld.txt”为相对路径,
结果为: