读取properties文件

1.首先要了解这两个东西:

getClass():取得当前对象所属的Class对象 = 路径没有 / 
getClassLoader():取得该Class对象的类装载器(个人简单的理解就是根目录src)= 路径自带 /

public class test {
    public static void main(String[] args) throws Exception {
        Properties ps=new Properties();
        ps.load(test.class.getClassLoader().getResourceAsStream("aa.properties")); //读取gg.properties也一样可以,文件夹没有影响
        System.err.println(ps.getProperty("test"));
    }

}

目录结构图

image


2.使用/作为跟目录,就不用使用getClassLoader()了;

public class CNTest {
    public static void main(String[] args) throws IOException {
        String fileName="/com/qq.properties";
        Properties ps=new Properties();
        ps.load(CNTest.class.getResourceAsStream(fileName));
        System.out.println(ps.getProperty("test"));
    }
}

目录结构:

image

原文地址:https://www.cnblogs.com/lq625424841/p/7151281.html