读取属性配置文件

一. 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")

猜你喜欢

转载自blog.csdn.net/zcx_hello/article/details/82770737