Class.getResource(String path)
path不以’/'开头时,默认是从此类所在的包下取资源;path 以’/'开头时,则是从ClassPath根下获取;
package testpackage;public class TestMain {
public static void main(String[] args) {
System.out.println(TestMain.class.getResource(\"\")); System.out.println(TestMain.class.getResource(\"/\")); }}输出结果
file:/E:/workspace/Test/bin/testpackage/file:/E:/workspace/Test/bin/
如果我们想在TestMain.java中分别取到1~3.properties⽂件,该怎么写路径呢?代码如下:
package testpackage;public class TestMain {
public static void main(String[] args) { // 当前类(class)所在的包⽬录
System.out.println(TestMain.class.getResource(\"\")); // class path根⽬录
System.out.println(TestMain.class.getResource(\"/\"));
// TestMain.class在 System.out.println(TestMain.class.getResource(\"2.properties\")); // TestMain.class在 // 3.properties 在 System.out.println(TestMain.class.getResource(\"subpackage/3.properties\")); // TestMain.class在 System.out.println(TestMain.class.getResource(\"/1.properties\")); }} Class.getClassLoader().getResource(String path)path不能以’/'开头时; path是从ClassPath根下获取; package testpackage;public class TestMain { public static void main(String[] args) { TestMain t = new TestMain(); System.out.println(t.getClass()); System.out.println(t.getClass().getClassLoader()); System.out.println(t.getClass().getClassLoader().getResource(\"\")); System.out.println(t.getClass().getClassLoader().getResource(\"/\"));//null }}输出结果 class testpackage.TestMain sun.misc.Launcher$AppClassLoader@1fb8ee3file:/E:/workspace/Test/bin/null 使⽤Class.getClassLoader().getResource(String path)可以这么写 package testpackage; public class TestMain { public static void main(String[] args) { TestMain t = new TestMain(); System.out.println(t.getClass().getClassLoader().getResource(\"\")); System.out.println(t.getClass().getClassLoader().getResource(\"1.properties\")); System.out.println(t.getClass().getClassLoader().getResource(\"testpackage/2.properties\")); System.out.println(t.getClass().getClassLoader().getResource(\"testpackage/subpackage/3.properties\")); }} 因篇幅问题不能全部显示,请点此查看更多更全内容