获取类路径下文件的绝对路径
在IDEA软件中,src是类的根路径。
package com.happy.reflection;
public class AboutPath {
public static void main(String[] args) {
String path = Thread.currentThread().getContextClassLoader().getResource("test.properties").getPath();
System.out.println(path);
}
}
运行结果:
如果test.properties在com文件夹下,
则修改相应代码为:
String path = Thread.currentThread().getContextClassLoader().getResource("com/test.properties").getPath();
读取test.properties里面的内容
package com.happy.reflection;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.Properties;
public class AboutPath {
public static void main(String[] args) throws Exception {
String path = Thread.currentThread().getContextClassLoader().getResource("test.properties").getPath();
FileReader reader = new FileReader(path);
Properties pro = new Properties();
pro.load(reader);
reader.close();
//通过key获取value
String message = pro.getProperty("importantMessage");
System.out.println(message);
}
}
运行结果: