Properties文件的读取
Maven项目,其中src/main/resources资源目录下,有一个properties文件
redis.propertites
ip=10.0.60.165 port=6379
第一种方式
通过获取到的URL转换为文件的绝对路径
public static void getValue_Reader() {
//该资源文件放在src/main/resources目录下,maven执行package命令时会将这些文件拷贝到target/classes目录下
String fileName = "redis.properties";
URL url = ClassLoader.getSystemResource(fileName);
String fullPath = url.toString();
fullPath = fullPath.substring("file:/".length());
System.out.println(fullPath);
Properties prop = new Properties();
try {
//文件较大,可以再使用BufferedReader进行包装
prop.load(new FileReader(fullPath));
} catch (Exception e) {
e.printStackTrace();
}
System.out.println(prop.get("ip"));
}
第二种方式
直接从类路径加载目录中获取资源文件
public static void getValue_Stream() {
String fileName = "redis.properties";
InputStream in = ClassLoader.getSystemResourceAsStream(fileName);
// InputStream in = Thread.currentThread().getContextClassLoader().getResourceAsStream(fileName);
Properties prop = new Properties();
try {
prop.load(in);
} catch (Exception e) {
e.printStackTrace();
}
System.out.println(prop.get("ip"));
}