• 读取配置文件工具类


    若使用getResourceAsStream读取配置文件失败,Files–>Project Structure–>modules–>source 找到resources文件夹,右键选择resourses,右边会出现resource folders。

    1、读取配置类工具类

    import java.util.Properties
     
    object PropertiesUtil {
     
      private val properties: Properties = new Properties
     
      /**
        *
        * 获取配置文件Properties对象
        *
        * @author yore
        * @return java.util.Properties
        * date 2018/6/29 14:24
        */
      def getProperties() :Properties = {
        if(properties.isEmpty){
          //读取源码中resource文件夹下的my.properties配置文件
          val reader = getClass.getResourceAsStream("/my.properties")
          properties.load(reader)
        }
        properties
      }
     
      /**
        *
        * 获取配置文件中key对应的字符串值
        *
        * @author yore
        * @return java.util.Properties
        * @date 2018/6/29 14:24
        */
      def getPropString(key : String) : String = {
        getProperties().getProperty(key)
      }
     
      /**
        *
        * 获取配置文件中key对应的整数值
        *
        * @author yore
        * @return java.util.Properties
        * @date 2018/6/29 14:24
        */
      def getPropInt(key : String) : Int = {
        getProperties().getProperty(key).toInt
      }
     
      /**
        *
        * 获取配置文件中key对应的布尔值
        *
        * @author yore
        * @return java.util.Properties
        * @date 2018/6/29 14:24
        */
      def getPropBoolean(key : String) : Boolean = {
        getProperties().getProperty(key).toBoolean
      }
     
    }
    

    读取方法:

    PropertiesUtil.getPropString("spark.checkout.dir")
    

    2、读取配置类工具类

    import java.util.Properties;
    
    public class MyConfig {
    
        private static Properties properties = new Properties();
    
        static {
            try {
                properties.load(MyConfig.class.getResourceAsStream("config.properties"));
            }catch (Exception e){
                throw new RuntimeException("配置文件加载出错");
            }
        }
    
        public static String getString(String propertyName) {
            return properties.getProperty(propertyName);
        }
    }
    

    读取方法:

    MyConfig.getString("xxxxxx")
    

    3、读取配置文件工具类

    原文地址:
    IDEA使用问题之getResourceAsStream读取配置文件失败

    /**
         * 获取连接
         * @return 返回JDBC得到的Connection
         * @throws ClassNotFoundException
         */
        public static Connection getConnection() throws ClassNotFoundException, IOException, SQLException {
     
            InputStream in = JDBCUtil.class.getClassLoader().getResourceAsStream("db.properties");
            Properties properties = new Properties();
            properties.load(in);
     
            String url =properties.getProperty("jdbc.url");
            String user =properties.getProperty("jdbc.user");
            String password =properties.getProperty("jdbc.password");
            String driverClass = properties.getProperty("jdbc.driverClass");
            Class.forName(driverClass);
            return DriverManager.getConnection(url,user,password);
        }
    

    4、 properties 读取工具类

    public class PropertyUtils {
        private static final Logger logger = LoggerFactory.getLogger(PropertyUtils.class);
        private static final Pattern PATTERN = Pattern.compile("\$\{([^\}]+)\}");
    
        public PropertyUtils() {
        }
    
        public static String get(Properties properties, String key) {
            String value = properties.getProperty(key);
            if (value == null) {
                logger.warn("get null value by key " + key + " from this properties !");
                return null;
            } else {
                Matcher matcher = PATTERN.matcher(value);
                StringBuffer buffer = new StringBuffer();
    
                while(matcher.find()) {
                    String matcherKey = matcher.group(1);
                    String matcherValue = properties.getProperty(matcherKey);
                    if (matcherValue != null) {
                        matcher.appendReplacement(buffer, matcherValue);
                    }
                }
    
                matcher.appendTail(buffer);
                return buffer.toString();
            }
        }
    
        public static Properties loadResourcesProperties(String fileName) {
            Properties properties = new Properties();
    
            try {
                String path = PathConstants.PROJECT_PATH + "\src\main\resources" + "\" + fileName;
                logger.info("Load properties file from absolute path : " + path);
                properties.load(new InputStreamReader(new FileInputStream(path), StandardCharsets.UTF_8));
            } catch (IOException var3) {
                var3.printStackTrace();
            }
    
            return properties;
        }
    
        public static Properties loadClassPathProperties(String fileName, Class anchorClass) {
            Properties properties = new Properties();
    
            try {
                String path = "/" + fileName;
                logger.info("Load properties file from relative path " + (anchorClass == null ? "" : "refer to " + anchorClass.getName() + ".class") + " : " + path);
                Class clazz = anchorClass == null ? PropertyUtils.class : anchorClass;
                InputStream inputStream = clazz.getResourceAsStream(path);
                if (inputStream == null) {
                    logger.error("Can not found properties file : [" + path + "]");
                    return properties;
                }
    
                properties.load(new InputStreamReader(inputStream, StandardCharsets.UTF_8));
            } catch (IOException var6) {
                var6.printStackTrace();
            }
    
            return properties;
        }
    
        public static Properties loadClassPathProperties(String fileName) {
            return loadClassPathProperties(fileName, (Class)null);
        }
    
        public static Properties extend(Properties targetProperties, Properties... extendProperties) {
            Properties[] var2 = extendProperties;
            int var3 = extendProperties.length;
    
            for(int var4 = 0; var4 < var3; ++var4) {
                Properties properties = var2[var4];
                targetProperties.putAll(properties);
            }
    
            return targetProperties;
        }
    
        public static String configDefaultProperty(Properties properties, String propertyName, String defaultValue) {
            if (properties.containsKey(propertyName)) {
                return properties.getProperty(propertyName);
            } else {
                logger.info("Can not get [" + propertyName + "], use default value [" + defaultValue + "] to config");
                return defaultValue;
            }
        }
    }
    
    public class ConfigPropertiesUtil {
    
        private static Logger logger = LogManager.getLogger(PropertiesUtil.class);
    
        private static String configPath = "/config.properties";
        private static Properties configProperties;
    
        public ConfigPropertiesUtil() {
        }
    
        public static String getConfigInfo(String key) {
            return configProperties == null ? null : configProperties.getProperty(key);
        }
    
        public static Properties loadProperties(String path) {
            logger.info("加载资源[" + path + "] ...");
            Properties prop = null;
            try {
                prop = PropertiesLoaderUtils.loadAllProperties(path);
            } catch (IOException e) {
                logger.error("加载资源[" + path + "]失败");
                logger.error(e.getMessage());
                e.printStackTrace();
            }
            return prop;
        }
    
        static {
            configProperties = loadProperties(configPath);
        }
    
    }
    
  • 相关阅读:
    C#如何给Listbox添加右键菜单
    [GraphQL] Query Lists of Multiple Types using a Union in GraphQL
    [GraphQL] Query GraphQL Interface Types in GraphQL Playground
    [GraphQL] Reuse GraphQL Selection Sets with Fragments
    [Dart] final vs const
    [GraphQL] Set variable and default value & alias
    [置顶] 【Git入门之十一】标签管理
    poj 3182 The Grove bfs
    hdu1166敌兵布阵
    <WinForm_1>初识WinForm编程
  • 原文地址:https://www.cnblogs.com/aixing/p/13327311.html
Copyright © 2020-2023  润新知