主要使用了spring-core-4.1.4.RELEASE-sources.jar 这个jar包里的 PropertiesLoaderUtils.loadProperties 方法。不说了,直接上代码:
package cn.lyj.util;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PropertiesLoaderUtils;
public class ExcutePro {
//读取.properties 结尾的配置文件用,getP, getParam
public static Map<String,String> getP(String path) throws Exception{
Resource resource = new ClassPathResource(path);
Properties props = PropertiesLoaderUtils.loadProperties(resource);
Map<String,String> param = new HashMap<String,String>((Map) props);
return param;
}
}
其中 Properties props ,java.util.Properties是对properties这类配置文件的映射,支持key-value类型和xml类型两种。
properties类实现了Map接口,所以很明显,他是用map来存储key-value数据,所以也注定存入数据是无序的,这个点需要注意。
针对key-value这种配置文件,是用load方法就能直接映射成map,非常简单好用。
Map<String, String> app = ExcutePro.getP("app.properties");
String ftpUrl = app.get("ftp.server.url");//Map类型,通过get("key")来得到结果
这样我们就能得到 app.properties 文件里的 ftp.server.url 的值
#ftp configure info
ftp.username = admin
ftp.password = 123456
ftp.server.url = 172.16.251.95
ftp.port = 21