zoukankan      html  css  js  c++  java
  • Java 读取application.properties配置文件中配置

      实际开发中若需要读取配置文件application.properties中的配置,代码如下。例:读取配置文件中name属性配置值:

      代码如下:

    import org.springframework.core.io.ClassPathResource;
    import org.springframework.core.io.Resource;
    import org.springframework.core.io.support.PropertiesLoaderUtils;
    
    import java.util.Properties;
    
    public class Test {
    
        /**
         * 通过配置文件名读取内容
         * @param fileName
         * @return
         */
        public static Properties readPropertiesFile(String fileName) {
            try {
                Resource resource = new ClassPathResource(fileName);
                Properties props = PropertiesLoaderUtils.loadProperties(resource);
                return props;
            } catch (Exception e) {
                System.out.println("————读取配置文件:" + fileName + "出现异常,读取失败————");
                e.printStackTrace();
            }
            return null;
        }
    
        public static void main(String[] args) {
            Properties properties = readPropertiesFile("application.properties");
            System.out.println(properties.getProperty("name"));
        }
    }
    

      执行结果:

      若使用上述方法读取出现中文乱码时,说明编码格式不一致,可使用下面可设置编码格式方法读取:

    /**
         * 通过配置文件名读取内容
         * @param fileName
         * @return
         */
        public Properties readPropertiesFile(String fileName) {
            Properties properties = new Properties();
            InputStream inputStream = Test.class.getClassLoader().getResourceAsStream(fileName);
            try {
                properties.load(new InputStreamReader(inputStream, "UTF-8"));
                return properties;
            } catch (Exception e) {
                logger.info("————读取配置文件:" + fileName + "出现异常,读取失败————");
                e.printStackTrace();
            }
            return null;
        }
    

      

  • 相关阅读:
    断开/删除 SVN 链接(.svn)的几种方法
    Android 中 ListView 常用属性合集
    Android 中 GridView 常用属性合集
    LeetCode-387-字符串中的第一个唯一字符
    LeetCode-374-猜数字大小
    LeetCode-290-单词规律
    LeetCode-278-第一个错误的版本
    LeetCode-383-赎金信
    LeetCode-367-有效的完全平方数
    LeetCode-350-两个数组的交集 II
  • 原文地址:https://www.cnblogs.com/Big-Boss/p/11252045.html
Copyright © 2011-2022 走看看