zoukankan      html  css  js  c++  java
  • Java程序读取Properties文件

    一、如果将properties文件保存在src目录下

    1.读取文件代码如下:

    /**
    * 配置文件为settings.properties
    * YourClassName对应你类的名字
    *
    / 
    private Properties LoadSettings() {
            Properties prop = new Properties();
            
            try {
                InputStream  in = new BufferedInputStream(YourClassName.class.getClassLoader().getResourceAsStream("/settings.properties"));
                prop.load(in); 
                in.close();
            } catch (Exception e) {
                System.err.println("Load settings.properties file Error! :
    "+ e.getMessage());
                prop = null;
            }
            
            return prop;
        }
    View Code

    2.使用上述代码来读取配置文件需要注意的是,配置文件必须放在src目录下,而不能放在子目录下:

        

    3. 特别注意,配置文件中的内容不需要加双引号;

    #不需要加双引号,加了之后获取到的内容可能就不是你想要的结果
    smtp_host="smtp-relay.gmail.com"
    smtp_user="debug@abc.com"
    smtp_password="debug"
    send_to="support@abc.com"
    smtp_port="465"
    
    
    #这样是对的
    smtp_host=smtp-relay.gmail.com
    smtp_user=debug@abc.com
    smtp_password=debug
    send_to=support@abc.com
    smtp_port=465

     二、如果将properties文件保存在与调用类相同目录下:

        调用的代码如下:

    直接使用 getClass().getResourceAsStream("filename.properties"); 即可

    Properties props = new Properties();
    props.load(getClass().getResourceAsStream("filename.properties"));
    View Code
  • 相关阅读:
    用tar命令把目标压缩包解压到指定位置
    testing and Deployment
    项目第二阶段进展
    注解使用中 @RequestMapping 和 @GetMapping @PostMapping 区别
    导入项目之最多的问题
    0 for前端之数据交互
    Required String parameter 'xxxxx' is not present] 报错400
    CDI Features
    初始化数据库问题
    mysql的时区问题
  • 原文地址:https://www.cnblogs.com/tommy-huang/p/7783000.html
Copyright © 2011-2022 走看看