读取properties文件
Posted love郎朗you
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了读取properties文件相关的知识,希望对你有一定的参考价值。
package com.hm.common.util;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
public class PropertiesUtil {
final static String fileName = "/conf/common.properties";
// 获取key所对应的值
public static String getProperties(String key) {
Properties prop = new Properties();
InputStream is = null;
try {
// properties文件放在src目录的下边
is = PropertiesUtil.class.getResourceAsStream(fileName);
if (is == null)
is = new FileInputStream(fileName);
prop.load(is);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (is != null) {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return prop.getProperty(key);
}
public static void main(String[] args) {
System.out.println( PropertiesUtil.getProperties("a.vn.salt"));
}
}
package com.la.util;
import java.util.PropertyResourceBundle;
import java.util.ResourceBundle;
import java.util.logging.Logger;
public class configResponse {
// protected static Logger logger = Logger.getLogger(configResponse.class);
protected static ResourceBundle configResponse;
protected static final String config_response_file="config/configResponse.properties";
static {
try {
configResponse = PropertyResourceBundle.getBundle(config_response_file);
} catch (Exception e) {
// TODO: handle exception
}
}
public static int getIntegerCode(String key) {
try {
if (configResponse.getString(key) != null) {
return Integer.parseInt(configResponse.getString(key));
}
} catch (Exception e) {
// logger.error("RESPONSE CODE FROM STRING TO INT THEN ERROR." , e) ;
}
return 0 ;
}
/**
* update by Brain
* @param key
* @return
*/
public static String getStringCode(String key){
return configResponse.getString(key)!=null?configResponse.getString(key):"";
}
public static int getIntegerCode(String key , int value ) {
try {
if (configResponse.getString(key) != null) {
return Integer.parseInt(configResponse.getString(key));
}
} catch (Exception e) {
// logger.error("RESPONSE CODE FROM STRING TO INT THEN ERROR." , e) ;
}
return value ;
}
public static String get(String key) {
return configResponse.getString(key);
}
public static String get(String key , String value) {
return configResponse.getString(key)==null?value:configResponse.getString(key) ;
}
}
以上是关于读取properties文件的主要内容,如果未能解决你的问题,请参考以下文章
如何读取jar包外的properties文件和log4j.properties