在读取配置文件的时候,如果我们写一个普通的Java 类,在调用的时候可能会多次的加载执行。但是例如配置文件啊,属性加载啊这些的数据,我们都是提前配置好的,不会经常改动,只需要在用的时候加载一次即可,那么我们可以使用单例模式
实现这个功能。
package com.test.connect.hive;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Objects;
import java.util.Properties;
public class HiveResourceInfo {
private static HiveResourceInfo resourceInfo=null;
private static Properties prop=null;
private HiveResourceInfo(){}
public static synchronized Properties getHiveConf() throws Exception {
if(null == resourceInfo){
resourceInfo=new HiveResourceInfo();
InputStream inputStream = HiveResourceInfo.class
.getClassLoader()
.getResourceAsStream("connInfo/hive/hiveConf.properties");
if (Objects.isNull(inputStream)) {
throw new Exception("can not read connInfo/hive/hiveConf.properties");
}
if(null == prop){
prop=new Properties();
}
prop.load(new InputStreamReader(inputStream,"UTF-8"));
}
return prop;
}
}
注意:本地读取文件和服务器上的路径可能不同,需要多加 ‘/’