Properties类操作.properties配置文件方法总结

一、properties文件

Properties文件是java中很常用的一种配置文件,文件后缀为“.properties”,属文本文件,文件的内容格式是“键=值”的格式,可以用“#”作为注释,java编程中用到的地方很多,运用配置文件,可以便于java深层次的解耦。

例如java应用通过JDBC连接数据库时,可以把数据库的配置写在配置文件 jdbc.properties:

driver=com.mysql.jdbc.Driver 
jdbcUrl=jdbc:mysql://localhost:3306/user 
user=root 
password=123456

这样我们就可以通过加载properties配置文件来连接数据库,达到深层次的解耦目的,如果想要换成oracle或是DB2,我们只需要修改配置文件即可,不用修改任何代码就可以更换数据库。

二、Properties类

java中提供了配置文件的操作类Properties类(java.util.Properties):

读取properties文件的通用方法:根据键得到value

    /**
     * 读取config.properties文件中的内容,放到Properties类中
     * @param filePath 文件路径
     * @param key 配置文件中的key
     * @return 返回key对应的value
     */
    public static String readConfigFiles(String filePath,String key) {
        Properties prop = new Properties();
        try{
            InputStream inputStream = new FileInputStream(filePath);
            prop.load(inputStream);
            inputStream.close();
            return prop.getProperty(key);
        }catch (Exception e) {
            e.printStackTrace();
            System.out.println("未找到相关配置文件");
            return null;
        }
    }

把配置文件以键值对的形式存放到Map中:

    /**
     * 把.properties文件中的键值对存放在Map中
     * @param inputStream 配置文件(inputstream形式传入)
     * @return 返回Map
     */
    public Map<String, String> convertPropertityFileToMap(InputStream inputStream) {
        try {
            Properties prop = new Properties();
            Map<String, String> map = new HashMap<String, String>();
            if (inputStream != null) {
                prop.load(inputStream);
                Enumeration keyNames = prop.propertyNames();
                while (keyNames.hasMoreElements()) {
                    String key = (String) keyNames.nextElement();
                    String value = prop.getProperty(key);
                    map.put(key, value);
                }
                return map;
            } else {
                return null;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

 

posted @ 2018-12-07 14:32  那心之所向  阅读(8306)  评论(0编辑  收藏  举报