目前实现的功能就是只需要把配置文件放在src根目录下,就能用文件名读取到文件中的key&value
主要的代码就是获取这个文件的绝对路径,不会因为文件路径的改变从而去修改Java源码。
1、getPath()方式
package org.example.reflect;
import java.io.InputStream;
import java.util.Properties;
public class IoProperties {
public static void main(String[] args) throws Exception{
//获取绝对路径
String path = Thread.currentThread().getContextClassLoader().getResource("文件名").getPath();
FileReader reader = new FileReader();
//新建配置对象
Properties properties = new Properties();
//将读取的文件流加载到配置对象
properties.load(reader);
//关闭流
reader.close();
//通过key获取value
String className = properties.getProperty("className");
//输出className
System.out.println(className);
}
}
2、以流的方式
package org.example.reflect;
import java.io.InputStream;
import java.util.Properties;
public class IoProperties {
public static void main(String[] args) throws Exception{
//以流的方式获取绝对路径
InputStream reader = Thread.currentThread().getContextClassLoader().getResourceAsStream("className.properties");
//以下不变
Properties properties = new Properties();
properties.load(reader);
reader.close();
//通过key获取value
String className = properties.getProperty("className");
System.out.println(className);
}
}