properties配置文件读取操作总结【java笔记】

声明:本文所有例子中的 properties 文件均放在 src 目录下,ecclipse 软件自动增加

一、基本概念

  1.1 

    properties文件,存储格式 键=值。

    properties文件特点:

      1、键值对格式
      2、“ = ”等号后面,值前面,的空格,会自动忽略掉
      3、值后面的空格,不会忽略
      4、“ = ”等号后面的双引号,不会忽略
      5、“ # ”井号后面内容,为注释,忽略

  1.2 Java的 Properties 类 属性映射(property map)

  是一种存储键/值对的数据结构。属性映射经常被用来存放配置信息。

  它有三个特性:

    1. 键和值斗志字符串

    2. 键/值对可以很容易地写入文件或从文件读出

    3. 用二级表存放默认值

  实现属性映射的Java类被称为 Properties(Java.util.Properties),此类是Java中比较重要的类,

  主要用于读取Java的配置文件,各种语言都有自己所支持的配置文件,配置文件中很多变量是经常改变的,

  这样做也是为了方便用户,让用户能够脱离程序本身去修改相关的变量设置,提高程序的可扩展性。

  此类是线程安全的:多个线程可以共享单个 Properties 对象而无需进行外部同步。

  构造方法:

    • Properties() 创建一个无默认值的空属性列表。
    • Properties( Properties defaults ) 创建一个带有指定默认值的空属性列表。

  它提供了几个主要的方法:
    getProperty ( String key):用指定的键在此属性列表中搜索属性。也就是通过参数 key ,得到 key 所对应的 value。

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

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

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

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

    注意:因为 Properties 继承于 Hashtable,所以可对 Properties 对象应用 put 和 putAll 方法。但不建议使用这两个方法,因为它们允许调用者插入其键或值不是 String 的项。相反,应该使用 setProperty 方法。

    如果在“不安全”的 Properties 对象(即包含非 String 的键或值)上调用 store 或 save 方法,则该调用将失败。

    类似地,如果在“不安全”的 Properties 对象(即包含非 String 的键)上调用 propertyNames 或 list 方法,则该调用将失败。

二、Java读取Properties文件的方法

  2.1 Java虚拟机(JVM)有自己的系统配置文件(system.properties)

//获取JVM的系统属性  
import java.util.Properties;  
public class ReadJVM {  
    public static void main(String[] args) {  
        Properties pps = System.getProperties();  
        pps.list(System.out);  
    }  
}  

  2.2 使用 J2SE API 读取 Properties 文件的六种方法

  方法一:java.util.Properties类的 load() 方法

    InputStream in = new BufferedInputStream(new FileInputStream(name));
    Properties p = new Properties();
    p.load(in);

  /**
     * 注意:配置文件一定要放到项目的根目录。
     */
    @Test
    public void run1() {
        try {
            FileInputStream is = new FileInputStream("src/my-ini.properties");
            Properties pop = new Properties();
            try {
                pop.load(is);
            } catch (IOException e) {
                e.printStackTrace();
            }
            Enumeration em = pop.propertyNames();
            while(em.hasMoreElements()) {
                String key = (String) em.nextElement();
                String value = pop.getProperty(key);
                System.out.println(key+"="+value);
            }
            
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }

  方法二:使用class变量的getResourceAsStream()方法

    InputStream in = JProperties.class.getResourceAsStream(name);
    Properties p = new Properties();
    p.load(in);

    /**
     * 注意:配置文件一定要放到当前目录下。
     * (目录层次也可以从src下面的文件夹开始但不必包含src,且不必包含反斜杠开头。) 
     * 本方法在 PropertiesDemo1 类中
     */
    @Test
    public void run2() {
        Properties pop = new Properties();
        try{
            InputStream in = PropertiesDemo1.class.getResourceAsStream("/my-ini.properties");
            pop.load(in);
        }catch(Exception ex) {
            ex.printStackTrace();
        }
        Enumeration em = pop.propertyNames();
        while(em.hasMoreElements()) {
            String key = (String) em.nextElement();
            String value = pop.getProperty(key);
            System.out.println(key+"="+value);
        }
        
        
    }

  方法三:使用 class.getClassLoader() 所得到的 java.lang.ClassLoader 的 getResourceAsStream() 方法

    InputStream in = JProperties.class.getClassLoader().getResourceAsStream(name);
    Properties p = new Properties();
    p.load(in);

  /**
     * 注意:
     * 配置文件一定要放在 bin 目录下
   * 注意 eclipse 软件自动将src中的配置文件复制到 bin 目录下
*/ @Test public void run3() { Properties pop = new Properties(); try{ InputStream in = PropertiesDemo1.class.getClassLoader().getResourceAsStream("my-ini.properties"); pop.load(in); }catch(Exception ex) { ex.printStackTrace(); } Enumeration em = pop.propertyNames(); while(em.hasMoreElements()) { String key = (String) em.nextElement(); String value = pop.getProperty(key); System.out.println(key+"="+value); } }

  方法四:使用 java.lang.ClassLoader 类的 getSystemResourceAsStream() 静态方法

    InputStream in = ClassLoader.getSystemResourceAsStream(name);
    Properties p = new Properties();
    p.load(in);

   /**
     * 注意:
     * 配置文件一定要放在 bin 目录下
     */
    @Test
    public void run4() {
        Properties pop = new Properties();
        try{
            InputStream in = ClassLoader.getSystemResourceAsStream("my-ini.properties");
            pop.load(in);
        }catch(Exception ex) {
            ex.printStackTrace();
        }
        Enumeration em = pop.propertyNames();
        while(em.hasMoreElements()) {
            String key = (String) em.nextElement();
            String value = pop.getProperty(key);
            System.out.println(key+"="+value);
        }
    }

  方法五:使用 java.util.ResourceBundle 类的 getBundle() 方法

    ResourceBundle rb = ResourceBundle.getBundle(name, Locale.getDefault());

  /**
     * 注意:
     * 配置文件一定要放在 bin 目录下
     */
    @Test
    public void run5() {
        ResourceBundle rs = ResourceBundle.getBundle("my-ini");
        
        String driver = rs.getString("driver");
        String url = rs.getString("url");
        String user = rs.getString("user");
        String password = rs.getString("password");
                
        System.out.println("driver="+driver);
        System.out.println("url="+url);
        System.out.println("user="+user);
        System.out.println("password="+password);
    }

  方法六:使用 java.util.PropertyResourceBundle 类的构造函数

  @Test
    public void run6() {
        File file = new File("src/my-ini.properties");
        try {
            BufferedInputStream in = new BufferedInputStream(new FileInputStream(file));
            try {
                PropertyResourceBundle prb = new PropertyResourceBundle(in);
                
                String driver = prb.getString("driver");
                String url = prb.getString("url");
                String user = prb.getString("user");
                String password = prb.getString("password");
                
                System.out.println("driver="+driver);
                System.out.println("url="+url);
                System.out.println("user="+user);
                System.out.println("password="+password);
            } catch (IOException e) {
                e.printStackTrace();
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }

引用博文: 

JAVA操作properties配置文件——总结(Locale&ResourceBundle& PropertyResourceBundle(http://blog.csdn.net/fanxiaobin577328725/article/details/52071310)

原文地址:https://www.cnblogs.com/mujingyu/p/7874797.html