java读取.properties配置文件

package http;

import java.io.InputStream;
import java.util.Properties;

public class Stweek
{
    static private String startdate = null;
    
    static private String totalweek = null;
    
    static
    {
        loads();
    }
    
    synchronized static public void loads()
    {
        if (startdate == null || totalweek == null)
        {
            InputStream is = Stweek.class.getResourceAsStream("/http/nsx.properties");
            Properties dbProps = new Properties();
            try
            {
                dbProps.load(is);
                startdate = dbProps.getProperty("username");
                totalweek = dbProps.getProperty("password");
            }
            catch (Exception e)
            {
                System.err.println("不能读取属性文件. " + "请确保db.properties在CLASSPATH指定的路径中");
            }
        }
    }
    
    public static String getStartdate()
    {
        if (startdate == null)
            loads();
        return startdate;
    }
    
    public static String getTotalweek()
    {
        if (startdate == null)
            loads();
        return totalweek;
    }
    
    public static void main()
    {
        System.out.println(Stweek.getStartdate());
        System.out.println(Stweek.getTotalweek());
    }

}

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

原文地址:https://www.cnblogs.com/jing1617/p/6424643.html