代码如下:

public class PropertiesUtil {

    private static Properties properties = null;
  //通常把配置文件放在与src同级的目录下面,则可以通过配置文件名直接访问到相应的配置文件
    public static Properties loadProperties(String propertyFile) {
        try {
            properties = new Properties();
            InputStream stream = PropertiesUtil.class.getResourceAsStream(propertyFile);
            properties.load(stream);
        } catch (FileNotFoundException e) {
            throw new RuntimeException("cannot find config file");
        } catch (IOException e) {
            e.printStackTrace();
        }
        return properties;
    }
    
    public static Properties loadProperties(FileInputStream stream) {
        try {
            properties = new Properties();
            properties.load(stream);
        } catch (FileNotFoundException e) {
            throw new RuntimeException("cannot find config file");
        } catch (IOException e) {
            e.printStackTrace();
        }
        return properties;
    }

    public static String getProperty(String key) {
        if (properties == null) {
            throw new RuntimeException("shou loadProperties first");
        }
        return properties.getProperty(key);
    }
  //如果没有找到相应的值,则会赋予一个默认值
    public static String getProperty(String key, String defaultValue) {
        if (properties == null) {
            throw new RuntimeException("shou loadProperties first");
        }
        return properties.getProperty(key, defaultValue);
    }

}