• Java中Properties类的操作


    Java中有个比较重要的类Properties(Java.util.Properties),主要用于读取Java的配置文件,就是像读取数据库账号密码一样,其配置文件常为.properties文件,格式为文本文件,文件的内容的格式是“键=值”的格式,文本注释信息可以用"#"来注释。

    Properties类继承自Hashtable,如下:

    它提供了几个主要的方法:

    1. getProperty ( String key),用指定的键在此属性列表中搜索属性。也就是通过参数 key ,得到 key 所对应的 value。

    2. load ( InputStream inStream),从输入流中读取属性列表(键和元素对)。通过对指定的文件(比如说下面的 test.properties 文件)进行装载来获取该文件中的所有键 - 值对。以供 getProperty ( String key) 来搜索。

    3. setProperty ( String key, String value) ,调用 Hashtable 的方法 put 。他通过调用基类的put方法来设置 键 - 值对。

    4. store ( OutputStream out, String comments),以适合使用 load 方法加载到 Properties 表中的格式,将此 Properties 表中的属性列表(键和元素对)写入输出流。与 load 方法相反,该方法将键 - 值对写入到指定的文件中去。

    5. clear (),清除所有装载的 键 - 值对。该方法在基类中提供。

    如果想使用Properties的话,完全可以在方法或者类里面声明一下代码:

    Properties p = new Properties();

    下面列出几个例子:

    随便新建一个配置文件(Test.properties)

    name=JJ
    Weight=4444
    Height=3333
     1 public class getProperties {
     2     public static void main(String[] args) throws FileNotFoundException, IOException {
     3         Properties pps = new Properties();
     4         pps.load(new FileInputStream("Test.properties"));
     5         Enumeration enum1 = pps.propertyNames();//得到配置文件的名字
     6         while(enum1.hasMoreElements()) {
     7             String strKey = (String) enum1.nextElement();
     8             String strValue = pps.getProperty(strKey);
     9             System.out.println(strKey + "=" + strValue);
    10         }
    11     }
    12 }

    但注意,在使用的时候,一定要在配置里面配置相关代码扫描此.properties结尾的文件。

    欢迎加入java技术群进行讨论,点我进群

  • 相关阅读:
    在数据库里进行分页处理
    new Date()在IE,谷歌,火狐上的一些注意项
    sql的一些小东西
    将sql数据库逆向生成PDM模型
    关于禁止在 .NET Framework 中执行用户代码。启用 "clr enabled" 配置选项
    MVC的Model层中的一些便签
    通过URL推送POST数据
    Python 关键字
    Python 标识符
    Python 注释(Python Comments)用法详解
  • 原文地址:https://www.cnblogs.com/suiyisuixing/p/7465528.html
Copyright © 2020-2023  润新知