场景分析:有时候我们可能会需要自己解析properties配置文件
废话不说,先上代码:
package com.yyp;
import java.util.*;
import java.io.*;
public class ParseProperties {
public static void main(String args[]) {
// 生成文件对象
File pf = new File(URLDecoder.decode(Thread.currentThread().getContextClassLoader().getResource("/").getPath() + CommonsConstans.REDIS_PROPERTIES, "UTF-8"));
// 生成文件输入流
FileInputStream inpf = null;
try {
inpf = new FileInputStream(pf);
} catch (Exception e) {
e.printStackTrace();
}
// 生成properties对象
Properties p = new Properties();
try {
p.load(inpf);
} catch (Exception e) {
e.printStackTrace();
}
// 输出properties文件的内容
System.out.println("name:" + p.getProperty("name"));
System.out.println("password:" + p.getProperty("password"));
}
}
URLDecoder.decode(Thread.currentThread().getContextClassLoader().getResource("/").getPath() + CommonsConstans.REDIS_PROPERTIES, "UTF-8");
这段代码,先获取项目的classPath路径,
CommonsConstans.REDIS_PROPERTIES
是文件名,然后进行UTF-8转码。
文件内容:
name=test
password=222222