1)使用Properties的load方法,将这个文件先加载进来,之后使用getProperty方法将对应键的值得到,比如: System.getProperties().load(“System.Properties.txt”);先加载System.Properties.txt文件 System.getProperties().getProperty(“DBType”);后将文件中键为DBType的值得到。 2)使用第一种方法键对应的值得灵活性比较大。还有一种方法是将不从文件中得到键对应的值。在程序中去设一个属性,比如: System.getProperties().setProperty(“DBType”,”SQLServer”);先设置一个键位DBType的属性 System.getProperties().getProperty(“DBType”);后通过getProperty方法得到DBType的值 实例:
package com.mmall.util;
import org.apache.commons.lang3.StringUtils;
import java.io.IOException; import java.io.InputStreamReader; import java.util.Properties;
/** 属性加载工具类 * Created by yangtianrui on 17/7/10. */ public class PropertiesUtils { private static final String propertyName = “mmall.properties”;
public static Properties properties = null; static { properties = new Properties(); try { // properties.setProperty("DB","sqlServer"); properties.load(new InputStreamReader(PropertiesUtils.class.getClassLoader() .getSystemResourceAsStream(propertyName),"utf-8")); // properties.load(); } catch (IOException e) { e.printStackTrace(); } } public static String getProperty(String propertyKey) { String value = properties.getProperty(propertyKey.trim()); if(StringUtils.isBlank(value)) { return null; } return value; } public static String getProperty(String key,String defauleValue) { String value = properties.getProperty(key,defauleValue); if(StringUtils.isBlank(key)) { return defauleValue.trim(); } return value.trim(); }} main函数: package com.mmall.util;
import org.hibernate.annotations.SourceType;
import java.util.Properties;
/** * Created by yangtianrui on 17/7/10. */ public class Yangtianrui_Test {
public static void main(String[] args) { String str = PropertiesUtils.getProperty("","alipay.callback.url"); System.out.println(str); //获取当前的系统属性 Properties prop = System.getProperties(); //System.load(aa.txt); //String s = PropertiesUtils.getStr(); //System.out.println(s); }}
