java中读取properties文件

java中读取properties文件

1. 概念
1.1 是什么?
java中的properties文件是一种配置文件,主要用于表达配置信息,文件类型是.properties,是一种文本文件,文件的内容是“键=值”的格式,通过符号“#”作为注释。
1.2 怎么用?
(1) 使用java.util.properties类来创建对象,该类继承了hashtable,因此得到的对象时一个map集合,可用通过集合的形式来获取properties文件的内容信息。
(2) properties的主要方法:

public String getProperty(String key):通过指定的key来获取对应的value值。
public synchronized void load(InputStream inStream) throws IOException:从输入流中获取配置文件的属性列表,通过指定文件的装载来获取该文件中的所有键 - 值对。以供 getProperty ( String  key) 来搜索。
public synchronized Object setProperty(String key, String value):通过调用hashtable的put()方法在配置文件中添加属性
 public void store(Writer writer, String comments) throws IOException:以适合使用 load 方法加载到 Properties 表中的格式,将此 Properties 表中的属性列表(键和元素对)写入输出流。与 load 方法相反,该方法将键 - 值对写入到指定的文件中去。

1.3 主要用途?
主要应用在程序中用来配置框架的配置文件,相对于xml的配置文件,操作更加简单高效,编辑也更加方便。
2. 实现思路
2.1 因为properties配置文件的相对固定,可以使用单例模式来提供实现,向外接口调用来设置属性。

2.2 获取属性值:获取文件的输入流,通过properties对象的load()方法获取输入流的属性列表到该对象中,通过对象的getProperties(String key)方法获取指定的key的value值。

2.3 添加属性列表:获取文件的输出流,通过properties方法的setProperties()方法设置属性列表,然后使用对象的store()方法通过输出流添加到配置文件中。
3. 代码实现

//查询配置文件的属性值
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

public class BizConfig {
    private static BizConfig instance = null;
    private static Properties prop =  new  Properties(); 
    private BizConfig() {
        InputStream in = this.getClass() .getResourceAsStream( "/biz.properties" );    
        try  {    
           prop.load(in);    
       }  catch  (IOException e) {    
           e.printStackTrace();    
       }   
    }

    public static synchronized BizConfig getInstance() {
        if(instance == null) {
            instance = new BizConfig();
        }
        return instance;
    }

    public String getValue(String key) {
        return prop.getProperty(key);
    }

    public static void main(String[] args) {
        BizConfig bizConfig = BizConfig.getInstance();
        System.out.println(bizConfig.getValue("key"));
    }
}

4. 总结
难点:
主要是流获取是否正确,往往获取失败就是获取的方式不对。
//相对路径‘/’
this.getClass() .getResourceAsStream( “/biz.properties” );
//绝对路径
this.getClass().getClassLoader().getResourceAsStream(“biz.properties”);

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值