java读取properties配置文件的方法

时间:2023-03-09 03:54:32
java读取properties配置文件的方法

app.properties

mail.smtp.host=smtp.163.com
mail.transport.protocol=smtp

  

import java.io.InputStream;
import java.util.Properties; import cn.zsmy.constant.Constant; public class ReadProperties { public static String host = null;
public static String protocol = null;
public static String auth = null;
public static String port = null;
public static String sender = null;
public static String password = null; //类加载后就执行,在需要的地方直接用类名.属性名即可,如ReadProperties.host,其他类要使用时需要将属性定义成public的,或者提供get方法
static{
loads();
} /**
* 读取properties
*/
public static void loads(){
if(host == null || protocol == null)
{
InputStream is = ReadProperties.class.getResourceAsStream("/app.properties");
Properties dbProps = new Properties();
try {
dbProps.load(is);
host = dbProps.getProperty("mail.smtp.host");
protocol = dbProps.getProperty("mail.transport.protocol");
auth = dbProps.getProperty("mail.smtp.auth");
port = dbProps.getProperty("mail.smtp.port");
sender = dbProps.getProperty("mail.sender");
password = dbProps.getProperty("mail.password");
}catch (Exception e) {
Constant.MY_LOG.error("不能读取属性文件. " +"请确保app.properties在CLASSPATH指定的路径中");
}
}
} /**
* 也可以调方法获取值,这样更万无一失,强烈建议用此方法,防止jvm内存回收后数据为空(看网上说静态属性是不会被回收的,除非类被回收)
* @return
*/
public static String getHost() {
if(host==null){
loads();
}
return host;
} public static String getProtocol() {
if(protocol == null){
loads();
}
return protocol;
} public static String getAuth() {
return auth;
} public static String getPort() {
return port;
} public static String getSender() {
return sender;
} public static String getPassword() {
return password;
} public static void main(String[] args) {
System.out.println(ReadProperties.host+"--------"+ReadProperties.protocol);
getHost();
System.out.println(ReadProperties.host+"--------"+ReadProperties.protocol);
}
}

这个方法不仅能够缓存配置文件内容,还能够做到自动加载配置文件的内容到内存,使用者完全不用考虑手动加载的过程,只需要在需要用到的地方直接调用getHost()即可(因为是静态方法,事先连对像也不用创建的),这样如果内存中有缓存,函数就会直接读取内存中的数据,节省时间,如果没有缓存也不用担心,系统会自动为你加载,使用者完全不用知道其是如何实现的,只需要知道我能直接调用函数获得想要的值就行了