读取属性配置文件

本文详细介绍如何使用Java的Properties和ResourceBundle类读取配置文件,包括从指定路径获取输入流,使用load()方法加载数据,遍历并打印key-value对,以及保存属性到新文件。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一. Properties读取配置文件

1、从目标路径test.properites中获取输入流对象

2、使用Properties类的load()方法从字节输入流中获取数据

3、直接打印Properties对象

4、使用Properties类的getProperty(String key)方法,根据参数key获取value

public void readProperties(String url){

 Properties prop = new Properties();     
        try{
            //读取属性文件,路径为url,eg:property/format.properties(src下具体路径),路径下文件有后缀
            InputStream in = new BufferedInputStream (new FileInputStream(url));
            prop.load(in);     //加载属性列表
            Iterator<String> it=prop.stringPropertyNames().iterator();  //属性文件key和value都为String类型
            while(it.hasNext()){
                String key=it.next();
                System.out.println(key+":"+prop.getProperty(key));
            }
            in.close();
            
            //保存属性到b.properties文件
            FileOutputStream oFile = new FileOutputStream("b.properties", true);//true表示追加打开
            prop.setProperty("phone", "10086");
            prop.store(oFile, "The New properties file");//后面的是注释信息,会以#开头显示
            oFile.close();
        }
        catch(Exception e){
            System.out.println(e);
        }

}

二.ResourceBundle读取配置文件

     //jdbc.properties为属性文件,放在当前路径目录下,这里文件不写后缀名

  ResourceBundle bundle = ResourceBundle.getBundle("jdbc");  //获取ResourceBundle
        DRIVERCLASS = bundle.getString("driverClass");    
        URL = bundle.getString("url");
        USER = bundle.getString("user");
        PASSWORD = bundle.getString("password")

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值