java中类路径下的绝对路径(通用路径)

类路径下的绝对路径(通用路径)

  • Class.forName("Myclass");像这种路径的缺点是:
    移植性差,在IDEA中默认的当前路径是project的根。如果不是IDEA,换到了其它位置,可能当前路径就不是project的根了,路径就会无效。
  • 一种比较通用的路径
    即使代码换位置了,这样编写仍然是通用的。(适用于任何操作系统)
    注意:使用以下通用方式的前提是:这个文件必须在类路径下。(放在src下的都是类路径下,src是类的根路径。)
  • 代码示例
public class Demo{
    public static void main(String[] args){

        /*
        Thread.currentThread():当前线程对象。
        getContextClassLoader():是线程对象的方法,
        可以获取到当前线程的类加载器对象。
        getResource():(获取资源)这是类加载器对象的方法,
        当前线程的类加载器默认从类的根路径下加载资源。
        */

        String path = Thread.currentThread()
                .getContextClassLoader()
                .getResource("classinfo.properties")
                .getPath();
        System.out.println(path);
    }
}

输出:
在这里插入图片描述
这里返回的是class文件所在的目录。所以不能获取java文件的路径,只能把.java改为.class:
getResource("Demo.class")
输出:
在这里插入图片描述

以流的形式返回路径

  • 代码示例
    在这里插入图片描述
import java.io.InputStream;
import java.util.Properties;

public class Demo{
    public static void main(String[] args) throws Exception{
        InputStream path = Thread.currentThread()
                .getContextClassLoader()
                .getResourceAsStream("classinfo.properties");
        Properties pro = new Properties();
        pro.load(path);
        path.close();
        String className = pro.getProperty("className");
        System.out.println(className);
    }
}

输出:
在这里插入图片描述

资源绑定器

  • 概述
    1、使用资源绑定器便于获取属性配置文件中的内容。
    2、只能绑定xxx.properties文件,但是路径后面的扩展名不能写。(.properties不能写)
    3、使用的时候,属性配置文件必须放到类路径下。
  • 代码示例
    在这里插入图片描述
import java.util.ResourceBundle;

public class Demo{
    public static void main(String[] args) throws Exception{
        ResourceBundle bundle = ResourceBundle.getBundle("classinfo");
        String date = bundle.getString("date");
        System.out.println(date);
    }
}

输出:
在这里插入图片描述

原文地址:https://www.cnblogs.com/yu011/p/13121948.html