JAVA访问配置文件总结

时间:2024-05-01 05:33:19

一、全局配置的简单 propertie 文件实现

 package com.testgs.utils;

 import java.util.*;
import java.io.*; public final class ARConfig { private Properties conf = new Properties();
private String prefix = "";
/**
* 全局配置文件名
*/
public static final String GLOBAL_CONF_FILE = "/analysisReportConfig.properties"; public ARConfig(String prefix) {
this.prefix = prefix;
loadConf();
} /**
* 取得属性文件实例
* @param prefix 各数据库连接前缀
* @return
*/
public synchronized static ARConfig getInstance(String prefix) {
return new ARConfig(prefix);
} public String getConfString(String name, String defaultValue) {
String result = getConfString(name);
result = (result == null) ? defaultValue : result;
return result;
} /**读取配置信息的 boolean 值
* @param name
* @param defaultValue
* @return
*/
public boolean getConfBoolean(String name, boolean defaultValue) {
boolean result = defaultValue;
String value = getConfString(name);
if (value != null) {
value = value.toLowerCase();
result = value.equalsIgnoreCase("true") || value.equalsIgnoreCase("yes");
}
return result;
} /**读取配置信息的 boolean 值,如果没有,默认为 false
* @param name
* @return
*/
public boolean getConfBoolean(String name) {
return getConfBoolean(name, false);
} /**
* 读取配置信息的 int 值
* @param name
* @param defaultValue
* @return
*/
public int getConfigInt(String name, int defaultValue) {
String intV = getConfString(name);
int result = defaultValue;
if (intV != null) {
try {
result = Integer.parseInt(intV.trim());
} catch (Exception e) {
e.printStackTrace();
}
}
return result;
} public String getConfString(String name) {
name = this.prefix + name;
return conf.getProperty(name);
} protected synchronized void loadConf() {
conf.clear();
InputStream input = null;
try {
input = this.getClass().getResourceAsStream(GLOBAL_CONF_FILE);
conf.load(input);
} catch (IOException e) {
throw new RuntimeException("找不到配置文件: " + GLOBAL_CONF_FILE);
} finally {
if (input != null)
try {
input.close();
} catch (Exception closeE) {
}
}
}
}

访问 properties 文件

更新中。。。