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;
        }
    

      

  • 相关阅读:
    dom 获取节点练习
    dom 节点的添加删除 与修改
    dom document属性练习
    ArrayList 去除重复元素
    ud类型聊天
    UDP数据发送
    指定标签所在div在新窗口打开
    日期Calendar
    Seraph介绍
    U盘cmd命令行修复
  • 原文地址:https://www.cnblogs.com/Big-Boss/p/11252045.html
Copyright © 2011-2022 走看看