zoukankan      html  css  js  c++  java
  • Java读取src下配置文件的问题

    博客原文:https://www.zjhuiwan.cn/info/20200331/4006622486333016.html

    读取配置文件的几种方式:

    (1)通过当前类获得根目录的路径然后获取文件。可以在非Web应用中读取配置资源信息,可以读取任意的资源文件信息。

     缺点:只能加载类src下面的资源文件,不适合装载大文件,否则会导致jvm内存溢出

    InputStream fstream = this.getClass().getClassLoader().getResourceAsStream("config.properties");
    
    
    //直接类调用TestController为当前类  “/”代表src目录下,不加则为该controller同包下
    InputStream is = TestController.class.getResourceAsStream("/config.properties");

    (2)可以以完全限定类名的方式加载资源后,直接的读取出来,且可以在非Web应用中读取资源文件。

    缺点:该方式只能加载类src下面的资源文件且只能读取.properties文件。

     // 获得资源包 
     ResourceBundle rb = ResourceBundle.getBundle("config.properties"); 

    (3)使用Spring框架提供的PropertiesLoaderUtils 获取,直接通过基于类路径的文件地址加载属性资源。

    Properties props=PropertiesLoaderUtils.loadAllProperties("config.properties"); 

    获取配置文件后,通过key取值

    InputStream is = ReadProperties.class.getResourceAsStream("/config.properties");
    		
    		Properties prop = new Properties();
    		prop .load(is);
    		is.close();
    
    		String name= prop .getProperty("name");
    		/*
    		 * 输出結果为:zjblog
    		 */
    		System.out.println(name);
    

    获取配置文件并遍历取出所有值,完整代码:

    src下config.properties文件

     public static void main(String[] args) {
            try {
                Properties prop = new Properties();
                InputStream in = InfoController.class.getResourceAsStream("/config.properties");
                prop.load(in);
                //获取所有key 遍历取值
                Set<Object> objects = prop.keySet();
                for (Object object : objects) {
                    // 注意编码格式,不然会乱码
                    String val = new String(prop.getProperty((String)object).getBytes("ISO-8859-1"), "utf-8");
                    System.out.println(val);
                }
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    运行结果

  • 相关阅读:
    flexpager权限控制文件crossdomain.xml
    MongoDB之mongodb.cnf配置
    MySQL之my.cnf配置
    在CentOS的profile文件中配置环境变量
    在CentOS上配置MySQL服务
    在CentOS上配置redis服务
    在CentOS上配置tomcat服务
    在CentOS上配置Tomcat服务脚本
    Netflix Hystrix — 应对复杂分布式系统中的延时和故障容错 转
    ETCD 简介 + 使用
  • 原文地址:https://www.cnblogs.com/sunonzj/p/12602921.html
Copyright © 2011-2022 走看看