java .properties配置文件一般都是以键值对为形式的例如
datasource-source.properties
database.name=springbatch
database.host=localhost
database.port=3306
database.username=root
database.password=123456liu
database.driverClass=com.mysql.jdbc.Driver
database.url=jdbc:mysql://${database.host}:${database.port}/${database.name}?characterEncoding=UTF-8&characterSetResults=UTF-8
工具类:
package com.ncsi.Demo1_SpringBatch.Utils;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import java.util.Set;
import org.apache.log4j.Logger;
public class PropertyUtil {
private static final Logger log=Logger.getLogger(PropertyUtil.class);
public static Properties databasePro;
static {
try{
databasePro=PropertyUtil.getProperties("database-source.properties");
}catch(Exception e){
log.warn("Warning database-source.properties load not correct, please check whether needed in current project");
}
}
/**
* 获取Properties对象
* @param propertyFileName
* @return
*/
public static Properties getProperties(String propertyFileName){
Properties props=new Properties();
InputStream st=Thread.currentThread().getContextClassLoader().getResourceAsStream(propertyFileName);
try {
props.load(st);
}catch(Exception e){
log.error(propertyFileName+" error occurred :ERROR ",e);
}
return props;
}
/**
* 获取Property的单个value值
* @param propertyFileName
* @param key
* @return
* @throws Exception
*/
public static String getPropertyValue(String propertyFileName,String key) throws Exception{
Properties props =new Properties();
InputStream st=Thread.currentThread().getContextClassLoader().getResourceAsStream(propertyFileName);
try{
props.load(st);
return props.getProperty(key);
}catch(Exception e){
log.error(propertyFileName+" error occurred :ERROR ",e);
}
return "";
}
/**
* 获取Property的所有Value值
* @param propertyFileName
* @return
*/
public static List<String> getAllValuesFromProperty(String propertyFileName){
List<String> PropValues=new ArrayList<String>();
Properties props=new Properties();
InputStream st=Thread.currentThread().getContextClassLoader().getResourceAsStream(propertyFileName);
try {
props.load(st);
Set<Object> keys=props.keySet();
for(Object k :keys){
PropValues.add(props.getProperty((String) k));
}
}catch(Exception e){
log.error(propertyFileName+" error occurred :ERROR ",e);
}
return PropValues;
}
/**
* 获取database-source.properties的某个value值
* @param propertyFileKey
* @return
*/
public static String getDatabaseByCode(String propertyFileKey){
return databasePro.getProperty(propertyFileKey);
}
}
测试类:
package com.ncsi.Demo1_SpringBatch.Utils;
import java.util.List;
import org.junit.Test;
public class propertyUtilTest {
@Test
public void testproperty(){
String root= PropertyUtil.getDatabaseByCode("database.username");
System.out.println(root);
List<String> values=PropertyUtil.getAllValuesFromProperty("database-source.properties");
System.out.println(values);
}
}