zoukankan      html  css  js  c++  java
  • 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;
            }
        }
  • 相关阅读:
    android Context 持有导致的内存泄漏
    android PreferenceFragment
    android 修改 SwitchPreferenceCompat 高度,内边距,字体大小
    Android MPAndroidChart RadarChart (蜘蛛网图)
    Bugtags 测试平台(支持ios、android)
    BlockCanary 一个轻量的,非侵入式的性能监控组件(阿里)
    RecyclerView item 状态错乱
    RecyclerView android:layout_width="match_parent" 无效
    android-async-http cancelRequests
    Android MultiDex
  • 原文地址:https://www.cnblogs.com/janson071/p/10082778.html
Copyright © 2011-2022 走看看