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

      

  • 相关阅读:
    动态表单实现客户端二次过滤及字段汇总统计
    开放一些常见功能的工具类代码
    动态表单
    客户中增加按钮提前判断是否撞单 并提示
    通过插件来对打印数据进行处理
    mac 升级10.12 php debug 环境 跑不起的解决 解决方案
    感觉世界变化太快...
    Mac 升级一次,php 就崩溃一次,有味,苹果....
    http://s22.app1105796624.qqopenapp.com/
    unity 2d 游戏优化之路 遇坑记录
  • 原文地址:https://www.cnblogs.com/Big-Boss/p/11252045.html
Copyright © 2011-2022 走看看