获取properties配置文件的值
package com.util;import org.apache.log4j.Logger;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
/**
* Properties文件读取工具类
*/
public class PropertiesUtil {
private static Logger log = Logger.getLogger(PropertiesUtil.class);
private Properties propertie;
public PropertiesUtil(String filePath) {
propertie = new Properties();
InputStream inputFile = null;
try {
inputFile = getClass().getResourceAsStream(filePath);
propertie.load(inputFile);
} catch (FileNotFoundException e) {
log.error("读取文件失败:" + e.getMessage());
} catch (IOException e) {
log.error("装载文件失败:" + e.getMessage());
} finally {
try {
if (null != inputFile) {
inputFile.close();
}
} catch (IOException e) {
log.error("关闭流失败:" + e.getMessage());
}
}
}
/**
* 根据key获取value
*
* @param key
* @return
*/
public String getValue(String key) {
if (propertie.containsKey(key)) {
return propertie.getProperty(key);
}
return null;
}
/**
* 根据指定资源路径加载单个资源文件,返回对应key的value值
*
* @param filePath 资源文件的路径的值
* @param key
* @return
*/
public static String getValue(String filePath, String key) {
String value = null;
InputStream is = null;
try {
Properties properties = new Properties();
is = new FileInputStream(filePath);
properties.load(is);
if (properties.containsKey(key)) {
value = properties.getProperty(key);
}
} catch (FileNotFoundException e) {
log.error("读取文件失败:" + e.getMessage());
} catch (IOException e) {
log.error("装载文件失败:" + e.getMessage());
} catch (Exception e) {
log.error("出错:" + e.getMessage());
} finally {
if (is != null) {
try {
is.close();
} catch (IOException e) {
log.error("关闭流失败:" + e.getMessage());
}
}
}
return value;
}
public static void main(String[] args) {
PropertiesUtil propertiesUtil = new PropertiesUtil("/config.properties");
System.out.println(propertiesUtil.getValue("test"));
System.out.println(PropertiesUtil.getValue("E:/workspace-idea/project/src/config.properties", "test"));
}
}
二、ResourceBundle获取
//注意Properties文件不需要带后缀名ResourceBundle resource = ResourceBundle.getBundle("config");
System.out.println(resource.getString("test"));
三、使用spring注解获取
@Value("${test}")private String test;
以上是 获取properties配置文件的值 的全部内容, 来源链接: utcz.com/z/516555.html