zoukankan      html  css  js  c++  java
  • Properties配置文件

    一、properties文件
    Properties文件是java中很常用的一种配置文件,文件后缀为“.properties”,属文本文件,文件的内容格式是“键=值”的格式,可以用“#”作为注释,java编程中用到的地方很多,运用配置文件,可以便于java深层次的解耦。例如java应用通过JDBC连接数据库时,通常需要在代码中写数据库连接字符串,下面贴出java通过JDBC连接数据库的代码(以mysql为例):

    String driver="com.mysql.jdbc.Driver";//mysql提供的Driver接口的实现类
    String jdbcUrl="jdbc:mysql:///user";//此处为"jdbc:mysql://localhost:3306/user"的简化形式,user为数据库名
    String user="root";
    String password="451535";
    Class.forName(driver);//通过反射动态实例化mysql数据库驱动类
    Connection conn= DriverManager.getConnection(jdbcUrl,user,password);
    1234567
    

    以上代码连接mysql数据库没有任何问题,但是我想换成Oracle数据库,问题就来了,不是不能改,而是我必须得到java源代码中修改代码,这样的硬代码耦合在java中一般不这么做(菜鸟程序员有可能)。所以,为了达到解耦的目的,我们可以用配置文件来储存数据库的连接字符串。下面贴一份保存数据库连接字符串的properties配置文件 jdbc.properties:
    driver=com.mysql.jdbc.Driver
    jdbcUrl=jdbc:mysql://localhost:3306/user
    user=root
    password=451535
    这样我们就可以通过加载properties配置文件来连接数据库,达到深层次的解耦目的,如果想要换成oracle或是DB2,我们只需要修改配置文件即可,不用修改任何代码就可以更换数据库。
    二、Properties类
    java中提供了配置文件的操作类Properties类(java.util.Properties):
    public class Properties extends Hashtable.可见Properties类继承了Hashtable,而HashTable又实现了Map接口,所以可对 Properties 对象应用 put 和 putAll 方法。但不建议使用这两个方法,因为它们允许调用者插入其键或值不是 String 的项。相反,应该使用 setProperty 方法。如果在“不安全”的 Properties 对象(即包含非 String 的键或值)上调用 store 或 save 方法,则该调用将失败。

    Properties的常用方法:
    1.setProperty(String key, String value)
    调用 Hashtable 的方法 put。
    2.
    getProperty(String key)
    用指定的键在此属性列表中搜索属性
    3.
    getProperty(String key, String defaultValue)
    用指定的键在属性列表中搜索属性。
    4.
    load(InputStream inStream)
    从输入流中读取属性列表(键和元素对)。
    5.
    load(Reader reader)
    按简单的面向行的格式从输入字符流中读取属性列表(键和元素对)。
    6.
    loadFromXML(InputStream in)
    将指定输入流中由 XML 文档所表示的所有属性加载到此属性表中。
    7.store(OutputStream out, String comments)
    以适合使用 load(InputStream) 方法加载到 Properties 表中的格式,将此 Properties 表中的属性列表(键和元素对)写入输出流。
    8.store(Writer writer, String comments)
    以适合使用 load(Reader) 方法的格式,将此 Properties 表中的属性列表(键和元素对)写入输出字符。
    9.storeToXML(OutputStream os, String comment)
    发出一个表示此表中包含的所有属性的 XML 文档。
    10.storeToXML(OutputStream os, String comment, String encoding)
    使用指定的编码发出一个表示此表中包含的所有属性的 XML 文档。
    下面通过代码的形式了解Properties的具体用法(通过JUnit单元测试的形式运行代码):
    *1.为properties对象添加属性和获取值*

    @Test   
    public void setAndGetProperty() {
                 Properties pro=new Properties();
                 //设置值
                 pro.setProperty("driver", "com.mysql.jdbc.Driver");
                 pro.setProperty("url", "jdbc:mysql///user");
                 pro.setProperty("user", "root");
                 pro.setProperty("password", "451535");
                 //获取值:
                 //1、getProperty(String key)方法  通过键获取值
                 String str= pro.getProperty("driver");
                 System.out.println(str);
                 //2、getProperty(String key, String defaultValue)重载方法
                 //当properties对象中没有所指定的键值时,显示给定的默认值
                 String str2=pro.getProperty("driver", "没有该值");
                 String str3=pro.getProperty("haha", "没有该值");
                 System.out.println(str2);
                 System.out.println(str3);
    
           }
    123456789101112131415161718192021
    

    运行结果:
    com.mysql.jdbc.Driver
    com.mysql.jdbc.Driver
    没有该值
    *2.以properties配置文件格式写入到硬盘中的某个文件夹(本例写入到D盘的others文件夹中):*

    @Test
    public void storePropertiesToHardFile() throws FileNotFoundException, IOException{
                 Properties pro=new Properties();
                 pro.setProperty("driver", "com.mysql.jdbc.Driver");
                 pro.setProperty("url", "jdbc:mysql///user");
                 pro.setProperty("user", "root");
                 pro.setProperty("password", "451535");
                 //1.通过字节流的形式
                 //store(OutputStream out, String comments)
                 //outputStream:字节输出流   comments:配置文件说明
                 pro.store(new FileOutputStream(new File("d:/others/jdbc.properties")), "数据库配置文件");
    
                 //2.通过字符流的形式
                 //store(Writer writer, String comments)
                 //writer:字符输出流   comments:配置文件说明
                 pro.store(new FileWriter("d:/others/jdbc.properties"),  "数据库配置文件");
           }
    123456789101112131415161718
    

    运行后效果:
    这里写图片描述

    *3.以XML配置文件格式写入到硬盘中的某个文件夹(本例写入到D盘的others文件夹中):*

    @Test
    public void storeXMLToHardFile() throws FileNotFoundException, IOException{
                 Properties pro=new Properties();
                 pro.setProperty("driver", "com.mysql.jdbc.Driver");
                 pro.setProperty("url", "jdbc:mysql///user");
                 pro.setProperty("user", "root");
                 pro.setProperty("password", "451535");
                 //1.不指定编码  默认为:UTF-8
                 //storeToXML(OutputStream os, String comment)
                 //因为XML不是文本文件,所以只能用字节流,为不能用字符流
                 pro.storeToXML(new FileOutputStream("d:/others/jdbc.xml"), "数据库配置文件");
    
                 //1.不指定编码
              //storeToXML(OutputStream os, String comment)
              //因为XML不是文本文件,所以只能用字节流,为不能用字符流
                 pro.storeToXML(new FileOutputStream("d:/others/jdbc2.xml"), "数据库配置文件", "GBK");
           }
    123456789101112131415161718
    

    运行后效果:
    这里写图片描述

    这里写图片描述

    这里写图片描述

    *4.以properties和XML配置文件格式写入到应用程序的某个文件夹(本例写入应用程序的classPath类路径下):*

    public void storeToClassPsth() throws FileNotFoundException, IOException{
                 Properties pro=new Properties();
                 pro.setProperty("driver", "com.mysql.jdbc.Driver");
                 pro.setProperty("url", "jdbc:mysql///user");
                 pro.setProperty("user", "root");
                 pro.setProperty("password", "451535");
                 pro.store(new FileOutputStream("src/jdbc.properties"), "数据库配置文件");
                 pro.storeToXML(new FileOutputStream("src/jdbc.xml") , "数据库配置文件");
           }
    12345678910
    

    运行后效果:
    这里写图片描述

    5.加载和读取配置文件(以properties文件为例)

    public void loadAndReadFile() throws FileNotFoundException, IOException{
                 Properties pro=new Properties();
                 //通过字节输入流
                 //load(InputStream inStream)
                 pro.load(new FileInputStream("src/sql.properties"));
                 //通过类加载器 获取当前类路径 
                 //类路径是指      / bin路径
                 pro.load(this.getClass().getResourceAsStream("/sql.properties"));
                  pro.load(this.getClass().getClassLoader().getResourceAsStream("sql.properties"));
    
                 //也可以使用当前上下文的类加载器,不用“/”
                  pro.load(Thread.currentThread().getContextClassLoader().getResourceAsStream("sql.properties"));
                 //通过字符输入流
                 //load(Reader reader)
                 pro.load(new FileReader("src/jdbc.properties"));
                 System.out.println(pro.get("driver"));
    //以上几种加载配置文件的方法都可以使用,此处都列举出来。
           }
    12345678910111213141516171819
    

    运行结果:
    com.mysql.jdbc.Driver
    6.附上通过读取配置文件JDBC连接数据库的代码干货:

    public Connection getConnection() throws Exception{
                 Properties info=new Properties();
                 info.load(this.getClass().getClassLoader().getResourceAsStream("jdbc.properties"));
                 String  driver=info.getProperty("driver");
                 String jdbcUrl=info.getProperty("jdbcUrl");
                 String user=info.getProperty("user");
                 String password=info .getProperty("password");
                 Class.forName(driver);
                 Connection connection=DriverManager.getConnection(jdbcUrl,user,password);
                 return connection;
           }
    123456789101112
    

    Java读取Properties文件:
    Java读取Properties文件的方法有很多,详见: Java读取Properties文件的六种方法
    但是最常用的还是通过java.lang.Class类的getResourceAsStream(String name)方法来实现
    ,如下可以这样调用:
    InputStream in = getClass().getResourceAsStream("资源Name");作为我们写程序的,用
    此一种足够。
    或者下面这种也常用:
    InputStream in = new BufferedInputStream(new FileInputStream(filepath));

    三、实例:
    根据key读取value
    读取properties的全部信息
    写入新的properties信息
    //关于Properties类常用的操作
    public class TestProperties {
    //根据Key读取Value
    public static String GetValueByKey(String filePath, String key) {
    Properties pps = new Properties();
    try {
    InputStream in = new BufferedInputStream (new FileInputStream(filePath));
    pps.load(in);
    String value = pps.getProperty(key);
    System.out.println(key + " = " + value);
    return value;

        }catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }
    
    //读取Properties的全部信息
    public static void GetAllProperties(String filePath) throws IOException {
        Properties pps = new Properties();
        InputStream in = new BufferedInputStream(new FileInputStream(filePath));
        pps.load(in);
        Enumeration en = pps.propertyNames(); //得到配置文件的名字
        
        while(en.hasMoreElements()) {
            String strKey = (String) en.nextElement();
            String strValue = pps.getProperty(strKey);
            System.out.println(strKey + "=" + strValue);
        }
        
    }
    //写入Properties信息
    public static void WriteProperties (String filePath, String pKey, String pValue) throws IOException {
        Properties pps = new Properties();
        
        InputStream in = new FileInputStream(filePath);
        //从输入流中读取属性列表(键和元素对) 
        pps.load(in);
        //调用 Hashtable 的方法 put。使用 getProperty 方法提供并行性。  
        //强制要求为属性的键和值使用字符串。返回值是 Hashtable 调用 put 的结果。
        OutputStream out = new FileOutputStream(filePath);
        pps.setProperty(pKey, pValue);
        //以适合使用 load 方法加载到 Properties 表中的格式,  
        //将此 Properties 表中的属性列表(键和元素对)写入输出流  
        pps.store(out, "Update " + pKey + " name");
    }
    
    public static void main(String [] args) throws IOException{
        //String value = GetValueByKey("Test.properties", "name");
        //System.out.println(value);
        //GetAllProperties("Test.properties");
        WriteProperties("Test.properties","long", "212");
    }
    

    }
    结果:
    Test.properties中文件的数据为:

    Update long name

    Sun Feb 23 18:17:16 CST 2014

    name=JJ
    Weight=4444
    long=212
    Height=3333
    总结:通过读取配置文件的形式可以实现代码的深层次解耦,在java编程中,配置文件的重要性更是不言而喻。java编程有一条不成文的规定就是:“约定大于配置,配置大于代码”意思就是能用约定的就不去配置,能用配置文件搞定的就不去写代码,真正牛逼的攻城狮(工程师)不是写代码,而是写配置。java的一些开源框架,如:Struts、Struts2、Hibernate、Spring、MyBatis等都大量的使用配置文件,我们在学习和工作中,都应该将“约定大于配置,配置大于代码”的思想运用到项目中,实现代码的解耦,体现出你比别人的高明之处,才能比别人优秀。

    转载自https://blog.csdn.net/yelang0/article/details/76449165

  • 相关阅读:
    [原创]Android插件化的一种实现
    [原创]HierarchyView的实现原理和Android设备无法使用HierarchyView的解决方法
    使用linux mint 安装无线网卡驱动
    Ubuntu下U盘变成只读的解决方法
    在Android源码中查找Java代码中native函数对应的C++实现
    Android Training Caching Bitmaps 翻译
    [转]获取app的内部储存路径
    [转]sudo找不到命令:修改sudo的PATH路径
    [转]CDN(内容分发网络)技术原理
    电视的应用开发注意事项[持续更新]
  • 原文地址:https://www.cnblogs.com/xiaxiaopi/p/14377033.html
Copyright © 2011-2022 走看看