使用懒汉模式(时间换空间)的单例模式读取配置文件AppConfig中的信息
配置文件AppConfig内容如下:
appConfig类:
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
public class appConfig {
private static appConfig instance;
private String paramterA;
private String paramterB;
private appConfig() {
readConfig();
}
public static appConfig GetInstance(){
if(instance == null){
instance = new appConfig();
}
return instance;
}
public String getParamterA() {
return paramterA;
}
public String getParamterB() {
return paramterB;
}
private void readConfig(){
Properties p = new Properties();
try{
p.load(getInputStream("AppConfig.properties"));
this.paramterA = p.getProperty("paramA");
this.paramterB = p.getProperty("paramB");
}catch ( IOException E){
E.printStackTrace();
}
}
private InputStream getInputStream(String path) throws IOException {
InputStream is = appConfig.class.getResourceAsStream(path);
if(is == null){
throw new FileNotFoundException();
}
return is;
}
}
注:
getInputStream方法中也可使用
InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream(path);
两种方法都为获取当前classpath的绝对路径的URI表示法
Thread.currentThread()同this不同,前者为获取当前线程
客户端:
public class Client {
public static void main(String[] args) {
appConfig config = appConfig.GetInstance();
String A = config.getParamterA();
String B = config.getParamterB();
System.out.println("paramA="+A+" "+"paramB="+B);
}
}
运行结果: