java中如何加载Properties文件

java中如何加载Properties文件

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);

}

}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值