JAVA实现读取自定义配置文件.properties的两种方法
如下图:
要获取resource下面自定义的配置文件,可使用下面的两种方法(要放在resource下面才能读取得到)
一、用getResourceAsStream(filePath)获取
这个项目上经常用到,主要是用到getClass().getResourceAsStream(filePath)来获取到文件流,然后将流加载入Properties,然后再读取,上代码:
Properties p = new Properties();
//获取文件的流
InputStream inStream = this.getClass().getResourceAsStream("/mini.properties");
if(inStream == null){
try {
throw new Exception("can not find file!");
} catch (Exception e) {
e.printStackTrace();
}
}
try {
p.load(inStream);
appId = p.getProperty("mini.appId");
if(!StringUtils.isEmpty(appId)){appId = appId.trim();}
System.out.println(appId);
appSecret = p.getProperty("mini.appSecret");
if(!StringUtils.isEmpty(appSecret)){appSecret = appSecret.trim();}
System.out.println(appSecret);
} catch (IOException e) {
try {
throw new Exception("load mini.properties fail!");
} catch (Exception e1) {
e1.printStackTrace();
}
}
System.out.println("load mini.properties success!");
我这里是用在SpringBoot启动的时候用@Configuration加载配置,把上面的代码放在构造函数里面,然后设计成单例模式。其实用什么方法加载不重要,重要的是能获取到配置文件的内容。运行完后出来的结果:
二、用ResourceBundle.getBundle(fileName)获取
这个要注意的是filename是不带后缀的,上代码
ResourceBundle resource = ResourceBundle.getBundle("mini");
try {
String appId = new String(resource.getString("mini.appId")
.trim()
.getBytes("ISO-8859-1"), "utf-8");//防止乱码
System.out.println(appId);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
我这个是在main里面运行的,运行结果:
这两种方式,都可以获取得到自定义的配置文件,看你怎么选择了。