如何 在 Java 中读取 .properties文件

属性缓存通常是一个单例静态实例,这样应用程序就不需要多次读取属性文件;因为对于任何对时间要求严格的应用程序,再次读取文件的 IO 成本都非常高。

下面的示例中, 我们从类路径中的文件“app.properties”中读取属性。
PropertiesCache充当加载属性的缓存。

该文件延迟加载属性,但只加载一次。

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import java.util.Set;
public class PropertiesCache
{
   private final Properties configProp = new Properties();

   private PropertiesCache()
   {
      //Private constructor to restrict new instances
      InputStream in = this.getClass().getClassLoader().getResourceAsStream("application.properties");
      System.out.println("Reading all properties from the file");
      try {
          configProp.load(in);
      } catch (IOException e) {
          e.printStackTrace();
      }
   }
   //Bill Pugh Solution for singleton pattern
   private static class LazyHolder
   {
      private static final PropertiesCache INSTANCE = new PropertiesCache();
   }
   public static PropertiesCache getInstance()
   {
      return LazyHolder.INSTANCE;
   }

   public String getProperty(String key){
      return configProp.getProperty(key);
   }

   public Set<String> getAllPropertyNames(){
      return configProp.stringPropertyNames();
   }

   public boolean containsKey(String key){
      return configProp.containsKey(key);
   }
}

在上面的代码中,我们使用了 Bill Pugh 技术来创建单例实例。

我们来测试一下上面的代码。

public static void main(String[] args)
{
  // 获取某个属性
  System.out.println(PropertiesCache.getInstance().getProperty("firstName"));
  System.out.println(PropertiesCache.getInstance().getProperty("lastName"));

  // 获取所有的属性
  System.out.println(PropertiesCache.getInstance().getAllPropertyNames());
}
日期:2020-09-17 00:09:25 来源:oir作者:oir