JAVA中的Properties类的基本应用

什么是Properties类

  1. Java中的类Properties(Java.util.Properties),主要用于读取java的配置文件。
  2. 在Java中,其配置文件常为.properties文件,格式为文本文件,文件的内容的格式是“键=值”的格式,文本注释信息可以用"#"来注释。
  3. Properties类继承自Hashtable,而哈希表则是链表加数组的结构。
  • Properties类中常见的方法

  1. getProperty ( String key),进行在文本文档中搜索也就是通过参数 key ,得到 key 所对应的 value。
  2. load ( InputStream inStream),从输入流中读取属性列表(键和元素对)。通过对指定的文件,进行装载来获取该文件中的所有键 值对。以供 getProperty ( String key) 来搜索。
  3.  setProperty ( String key, String value) ,调用 Hashtable 的方 put 。他通过调用基类的put方法来设置 键 - 值对。
  4.  store ( OutputStream out, String comments),以适合使用 load 方法加载到 Properties 表中的格式,将此 Properties 表中的属性列表(键和元素对)写入输出流。与 load 方法相反,该方法将键 - 值对通过输出流写入到指定的文件中去。(特别的是 String comments是标注会以#后来呈现)
  5. clear (),清除所有装载的 键 - 值对。该方法在基类中提供。
  • 如何读取Properties文件

  1. 通常通过BufferedInputStream中FileInputStream传入Properties文件。

  • 以下是通过 BufferedInputStream和BufferedOutputStream分别读取和写入Properties文件,并且通过Load方法以及Store方法来载入和写出Properties文件。

  • package com.my.hyz4;
    
    import java.io.BufferedInputStream;
    import java.io.BufferedOutputStream;
    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.util.Properties;
    
    public class Demo03 {
    	public static void main(String[] args) {
    		 try (BufferedInputStream bis = new BufferedInputStream(new FileInputStream("d:\\tupian\\hba.properties"))) {
    			Properties prpos = new Properties();
    			 prpos.load(bis);
    			 System.out.println(prpos.get("aa"));
    			 System.out.println(prpos.size());
    		} catch (IOException e) {
    			e.printStackTrace();
    		}
    		 //输出流负责写文件
    		 Properties properties = new Properties();
    		 properties.putIfAbsent("F1", "11111");
    		 properties.putIfAbsent("F2", "21111");
    		 properties.putIfAbsent("F3", "31111");
    		 properties.putIfAbsent("F4", "41111");
    		 try (//使用输出流,将Properties中的KV键值对写入文件当中
    		 BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("d:\\tupian\\rng.properties"))) {
    			properties.store(bos, "just do it");
    		} catch (IOException e) {
    			// TODO Auto-generated catch block
    			e.printStackTrace();
    		}
    	}
    }
    

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值