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
原文地址:https://www.cnblogs.com/tommy-huang/p/7783000.html