java读取properties属性文件值方法

 

方式一:ResourceBundle这个类可是实现读取properties文件来获取值

在java中:

  1. public class ResourceBundleReader {
     public final static Object initLock = new Object();
  2.  private final static String PROPERTIES_FILE_NAME = "property";
  3.  private static ResourceBundle bundle = null;
  4.  static {
      try {
       if (bundle == null) {
        synchronized (initLock) {
         if (bundle == null)
          bundle = ResourceBundle.getBundle(PROPERTIES_FILE_NAME,Locale.CHINA);
        }
       }
      } catch (Exception e) {
       System.out.println("读取资源文件property_zh.properties失败!");
      }
     }
     public static ResourceBundle getBundle() {
      return bundle;
     }
     public static void setBundle(ResourceBundle bundle) {
      bundle = bundle;
     }
     
     
    }

在.properties文件中:

driverName=com.mysql.jdbc.Driver
url=xxxxx/:3307/9zgame?
user=root
password=xxxxxx

文件名字为:property_zh.properties。后zh根据Locale.CHINA一致的,如果Locale.ENGLISH,则文件名为:property_en.properties

方式二:使用commons组件。

需要使用jar包:commons-configuration-1.3.jar,commons-lang-2.3.jar,commons-collections.3.2.jar,commons-logging.jar

public class ConfigReader {

 private static ConfigReader instance =new ConfigReader();
 public static Configuration config ;
 private ConfigReader(){
  try{
   config = new PropertiesConfiguration("test.properties");
  }catch(NestableRuntimeException e2){
   System.out.println("properties read error...");
  }catch(ConfigurationException e3){
   System.out.println("properties read error...");
  }
 }
 
 public static  ConfigReader getInstance(){
  return instance ;
 }
 
 public static void main(String args[]) throws RemoteException, NestableRuntimeException, ConfigurationException {
  System.out.println(ConfigReader.getInstance().config.getProperty("userid"));
 }
}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值