Properties类

来源:互联网 发布:大数据100g百度云 编辑:程序博客网 时间:2024/05/28 11:50

Properties  :继承自Hashtable

要求键和值都必须是字符串,都不能为空

Properties一般用于读取配置文件,如.properties结尾的配置文件。

配置文件如:

注意:配置文件中间不要用空格。例如:

username    =    lss

步骤如下:

Properties pro =new Properties();

Pro.load(“路径”);

1)    Object obj = pro.get(key); // 继承的父类hashtable中的方法。此时的key和返回的value都是Object类型。

2)    String s = obj.getProperty(key); // 此时的key是配置文件中的key,返回的结果s是对应的配置文件中的value

需要注意的是 url的获取可以有好几种方式:

publicclassProTest {

   publicstaticvoid main(String[]args) throws Exception { 

      Propertiesproperties=newProperties();

// 通过绝对路径加载配置文件

properties.load(newFileInputStream("d:\\workspace01\\justfortest\\user.properties"));

   System.out.println(properties.getProperty("url"));

 

// 通过相对路径加载配置文件

properties.load(new FileInputStream("user.properties"));

   System.out.println(properties.getProperty("uname"))


// 将配置文件放到类下

//通过类加载器

properties.load(ProTest.class.getClassLoader().getResourceAsStream("cn/liz/test02/user.properties"));     

System.out.println(properties.getProperty("uname"))      

 

// 通过反射 classLoader的区别是前面加上 /

properties.load(ProTest.class.getResourceAsStream("/cn/liz/test02/user.properties"));   

  System.out.println(properties.getProperty("uname"));


// 通过当前线程最稳定

properties.load(Thread.currentThread().getContextClassLoader().getResourceAsStream("cn/liz/test02/user.properties"));

System.out.println(properties.get("upassword"));

   }

}

程序结果是:

www.baidu.com
lzz
lzz
lzz
123456

能够正确读取到,没有问题。


原创粉丝点击