您的位置:首页 > 编程语言 > Java开发

JAVA访问配置文件总结

2015-08-07 16:43 260 查看
一、全局配置的简单 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 文件
更新中。。。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: