获取Properties文件

package com.chinamobile.epic.tako.v2.query.commons;

import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PropertiesLoaderUtils;

import java.io.*;
import java.util.Iterator;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.ConcurrentHashMap;

public class PropertiesUtilsBase {

/**
* 获取属性文件
* @param path example: c:\\my.properties
* @return
*/
public static Properties loadFromFileSystem(String path) {
Properties props = new Properties();
try {
File file = new File(path);
InputStream in = new BufferedInputStream(new FileInputStream(file));

//解决中午乱码问题--因为字节流无法读取中文,所以采用reader把inputStream转换成reader用字符流来读取中文
BufferedReader bf = new BufferedReader(new InputStreamReader(in));
props.load(bf);
in.close();
} catch (Exception e) {
return null;
}
return props;
}

/**
* 从classpath中获取属性文件
*
* @param path graphite/graphiteTargets.properties
* @return
*/
public static Properties loadFromClassPath(String path) {
Resource resource = new ClassPathResource(path);
Properties prop = null;
try {
prop = PropertiesLoaderUtils.loadProperties(resource);
} catch (IOException e) {
e.printStackTrace();
}
return prop;
}

public static Map<String, String> asMap(Properties properties) {
if (properties == null) {
return null;
}

Map<String, String> entryMap = new ConcurrentHashMap<String, String>();

for (Map.Entry<Object, Object> entry : properties.entrySet()) {
String key = entry.getKey().toString();
String value = entry.getValue().toString();
entryMap.put(key, value);
}
return entryMap;
}

/**
* 显示所有key,value
*
* @param properties
*/
public static void showKeysAndValues(Properties properties) {
if (properties == null) {
System.out.println("properties == null");
return;
}
Iterator<Map.Entry<Object, Object>> it = properties.entrySet().iterator();

System.out.println("======下面将显示所有<key,value>值---方式1============");
while (it.hasNext()) {
Map.Entry<Object, Object> entry = it.next();
Object key = entry.getKey().toString();
Object value = entry.getValue();
System.out.println("<" + key + "," + value + ">");
}
}
}

使用@Bean方式获取Properties

@Bean
public Properties quartzProperties() throws IOException {
PropertiesFactoryBean propertiesFactoryBean = new PropertiesFactoryBean();
propertiesFactoryBean.setLocation(new ClassPathResource("/quartz.properties"));
propertiesFactoryBean.afterPropertiesSet();
return propertiesFactoryBean.getObject();
}