java项目中读取Properties文件

java项目中读取property文件还是相当简单的。

这里会涉及到一个Properties类。这里简单介绍一下Properties类。

上图是Properties类的继承关系,可以看到Properties类继承自Hashtable类。

Properties类表示持久化的set数据。可以通过stream获取,也可以保存到stream中。

在Properties中,key和value都是String类型。

下面是我自定义(好吧,其实是曾老师的代码改了改)的 读取java项目中的Properties文件 的工具类。

/**
 * Properties工具类
 * @author admin
 *
 */
public class PropertyUtils {
    
    private static Properties properties;
    private File file = null;
    private static long lastModified = 0L;
    private static String DEFAULT_VALUE = null;
    
    private static Log log = LogFactory.getLog(PropertyUtils.class);
    private static String PROPERTIE_FILE_NAME = null;
    
    /**
     * 构造函数
     * @param propertyFileName
     */
    private PropertyUtils(String propertyFileName) {
        try {
          PROPERTIE_FILE_NAME = propertyFileName;
          Resource resource = new ClassPathResource(PROPERTIE_FILE_NAME);
          file = resource.getFile();
          lastModified = file.lastModified();
          if (lastModified == 0) {
            log.error(PROPERTIE_FILE_NAME + " file does not exist!");
          }
          properties = new Properties();
          properties.load(resource.getInputStream());

        } catch (IOException e) {
          log.error("can not read config file " + PROPERTIE_FILE_NAME);
        }
        log.debug(PROPERTIE_FILE_NAME + " loaded.");
      }
    
    /**
     * 获取实例
     * @param propertyFileName
     * @return
     */
    public static PropertyUtils getInstance(String propertyFileName) {
    return new PropertyUtils(propertyFileName);
  }
    
    /**
     * 获取配置文件中的Property
     * @param key
     * @return
     */
    public final String getProperty(String key) {
    return getProperty(key, DEFAULT_VALUE);
  }

  public final String getProperty(String key, String defaultValue) {
    long newTime = file.lastModified();
    if (newTime == 0) {
      return defaultValue;
    } else if (newTime > lastModified) {
      try {
        properties.clear();
        Resource resource = new ClassPathResource(PROPERTIE_FILE_NAME);
        properties.load(new FileInputStream(resource.getFile()));
      } catch (Exception e) {
        e.printStackTrace();
      }
    }
    lastModified = newTime;
    return properties.getProperty(key) == null ? defaultValue : properties
        .getProperty(key);
  }

}

使用方法很简单,如下

  String urlStr  = PropertyUtils.getInstance("url.properties").getProperty("save.url"); 
原文地址:https://www.cnblogs.com/cuglkb/p/7002407.html