Java 读写属性文件示例

Java 读写属性文件示例

原文: https://howtodoinjava.com/java/io/java-loadreadwrite-properties-file-examples/

如今,任何复杂的应用程序都需要某种配置。 有时我们需要将此配置为只读(通常在应用程序启动时读取),有时(或很少)我们需要写回或更新这些属性配置文件上的内容。

在这个简单易用的教程中,学习使用Properties.load()方法读取 Java 中的属性文件。 然后,我们将使用Properties.setProperty()方法将的新属性写入文件中。

用于例如app.properties的属性文件

下面是一个示例属性文件,我们将在示例应用程序中使用它。

firstName=Lokesh
lastName=Gupta
blog=howtodoinjava
technology=java

读取属性文件示例

在大多数应用程序中,属性文件在应用程序启动期间仅读取一次,然后进行缓存。 每当需要通过键来获取属性值时,您都将查询属性缓存并从中获取值。 该高速缓存通常是一个单例实例,因此应用程序不会多次读取属性文件;因此,应用程序无法读取属性文件。 因为对于当今世界上时间紧迫的应用程序,再次读取 IO 的成本非常高。

在下面的示例中,我给出了属性缓存单例实例的此类示例。 随时根据您的需要进行修改/建议。

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("app.properties");
      System.out.println("Read all properties from 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 技术创建单例实例。

阅读更多: Java 中的单例设计模式

让我们测试上面为属性缓存创建的代码。

public static void main(String[] args)
{
  //Get individual properties
  System.out.println(PropertiesCache.getInstance().getProperty("firstName"));
  System.out.println(PropertiesCache.getInstance().getProperty("lastName"));

  //All property names
  System.out.println(PropertiesCache.getInstance().getAllPropertyNames());
}

Output:

Read all properties from file
Lokesh
Gupta
[lastName, technology, firstName, blog]

写入属性文件示例

就个人而言,我找不到从应用程序代码修改属性文件的任何充分理由。 仅当您准备将数据导出到仅需要此格式的数据的第三方供应商/或应用程序时,这才有意义。

因此,如果您面临类似的情况,请在PropertiesCache.java中创建另一个方法,如下所示:

public void setProperty(String key, String value){
  configProp.setProperty(key, value);
}

并以这种方式使用上述方法将写入新属性到属性文件中。

PropertiesCache cache = PropertiesCache.getInstance();
if(cache.containsKey("country") == false){
 cache.setProperty("country", "INDIA");
}
//Verify property
System.out.println(cache.getProperty("country"));  

Output:

Read all properties from file
INDIA 

这是与使用 Java 读写属性文件相关的这个简单易懂的教程的全部内容

给我留言是不清楚或您有任何疑问。

祝您学习愉快!

参考:Properties Java 文档