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

      

  • 相关阅读:
    Centos7 安装配置Elasticsearch
    单例模式
    Eclipse上部署maven项目
    单点登录
    各eclipse插件的作用
    eclipse中安装Subclipse插件
    往idea中导入已有的web项目
    maven 项目部署
    【转帖】算法刷题网站
    混淆矩阵-MATLAB代码详解
  • 原文地址:https://www.cnblogs.com/Big-Boss/p/11252045.html
Copyright © 2011-2022 走看看