读properties文件

太无聊了,写个读properties文件的类方便以后直接copy

private String fileName;
private Properties properties;
private FileInputStream inputFile;
private String filePath;

// Constructor
public ProUtil() {
this.properties = new Properties();
}

// get path of property file
public String getConfigPath() {
String strClassName = getClass().getName();
String strPackageName = "";
if (getClass().getPackage() != null) {
strPackageName = getClass().getPackage().getName();
}
String strClassFileName = "";
if (!"".equals(strPackageName)) {
strClassFileName = strClassName.substring(
strPackageName.length() + 1, strClassName.length());
} else {
strClassFileName = strClassName;
}
URL url = null;
url = getClass().getResource(strClassFileName + ".class");
String strURL = url.toString();
try {
strURL = java.net.URLDecoder.decode(strURL, "UTF-8");
System.out.println("strURL : " + strURL);
} catch (Exception ex) {
ex.printStackTrace();
}
strURL = strURL.substring(strURL.indexOf('/') + 1,
strURL.lastIndexOf('/') + 1);
return strURL;
}

// file configuration
private void initFileConfig() {
try {
filePath = this.getConfigPath();
filePath += fileName;
System.out.println("filePath is : " + filePath);
inputFile = new FileInputStream(filePath);
properties.load(inputFile);
inputFile.close();
} catch (FileNotFoundException e) {
System.out.println("配置文件路径错误");
} catch (IOException e) {
System.out.println("配置文件度取失败");
} catch (Exception ex) {
ex.printStackTrace();
}
}

// read Value by key from input parameter "fileName"
public String readValueByKey(String fileName, String key) {
try {
String value = "";
this.fileName = fileName;
initFileConfig();
if (properties.containsKey(key)) {
value = properties.getProperty(key);
return value;
} else
return value;
} catch (Exception ex) {
ex.printStackTrace();
return "";
}
}

// read all info from property file
public String readAllValues(String fileName) {

try {
@SuppressWarnings("rawtypes")
Enumeration en = properties.propertyNames();
while (en.hasMoreElements()) {
String key = (String) en.nextElement();
String value = properties.getProperty(key);
System.out.println("Key is : " + key + " Value is : " + value);
}
} catch (Exception ex) {
ex.printStackTrace();
return "";
}
return null;
}

// read Value by key
// public String getValue(String key) {
// if (propertie.containsKey(key)) {
// String value = propertie.getProperty(key);
// return value;
// } else {
// return "";
// }
// }
//test
public static void main(String[] args) {
ProUtil property = new ProUtil();
System.out.println(property.readValueByKey("xxx.properties",
"a"));
System.out.println(property.readAllValues("xxx.properties"));
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值