这种路径的缺点:移植性差,在IDEA中默认的路径是project路径的根
当这个代码离开了IDEA,换到了其他位置,可能当前代码就会报错了
前提:在类路径下(src下)
String path = Thread.currentThread().getContextClassLoader().getResource("要获取的资源").getPath(); Thread.currentThread() 获取当前对象 getContextClassLoder() 获取当前线程的类加载器对象 getResource() 【获取资源】当前线程的类加载器默认从类的根路径(即src)下加载资源以上代码可以拿到一个文件的绝对路径,举个例子
public class Test { public static void main(String[] args) throws Exception{ String path = Thread.currentThread().getContextClassLoader().getResource("com/sdut/wwg/Demo").getPath(); System.out.println(path); } }输出结果为
/C:/Users/dell/IdeaProjects/demo1/out/production/Demo/com/sdut/wwg/Demo
注意:只有资源文件放在src下才可以用这种方法获取。这种方法不可以获取java文件的路径,因为IDEA中的src并不是磁盘上的src。而是字节码文件所在的目录,因为这个目录下没有java文件,所以不能使用这种方法来获取java文件
只能绑定XXX.properties文件,并且路径必须在类路径下
public class Test { public static void main(String[] args) throws Exception{ //不用加后缀 ResourceBundle bundle = ResourceBundle.getBundle("text"); //获取className的value值 String name = bundle.getString("className"); System.out.println(name); } }