Java Properties getProperty() 方法



描述

Java Properties getProperty(String key) 方法在此属性列表中搜索具有指定键的属性。如果在此属性列表中找不到该键,则会递归检查默认属性列表及其默认值。如果找不到该属性,则该方法返回null

声明

以下是java.util.Properties.getProperty() 方法的声明

public String getProperty(String key)

参数

key - 属性键。

返回值

此方法返回此属性列表中具有指定键值的属性值。

异常

Java Properties getProperty(String key, String defaultValue) 方法

描述

Java Properties getProperty(String key) 方法在此属性列表中搜索具有指定键的属性。如果在此属性列表中找不到该键,则会递归检查默认属性列表及其默认值。如果找不到该属性,则该方法返回默认值参数。

声明

以下是java.util.Properties.getProperty(String key, String defaultValue) 方法的声明

public String getProperty​(String key, String defaultValue)

参数

key - 属性键。

返回值

此方法返回此属性列表中具有指定键值的属性值。

异常

从 Properties 示例中根据键获取值

以下示例演示了如何使用 Java Properties getProperty(String key) 方法从 Properties 中根据键获取值。我们创建了一个 Properties 对象。然后添加了一些条目。使用 getProperty() 方法检索并打印了一个值。

package com.tutorialspoint;

import java.util.Properties;

public class PropertiesDemo {
   public static void main(String[] args) {
      Properties properties = new Properties();

      //populate properties object
      properties.put("1", "tutorials");
      properties.put("2", "point");
      properties.put("3", "is best");

      System.out.println("Properties elements: " + properties);
      System.out.println("Value: " + properties.getProperty("1"));
   }
}

输出

让我们编译并运行以上程序,这将产生以下结果。

Properties elements: {1=tutorials, 2=point, 3=is best}
Value: tutorials

从 Properties 示例中获取默认值

以下示例演示了如何使用 Java Properties getProperty(String key, String defaultValue) 方法从 Properties 中根据键获取值。我们创建了一个 Properties 对象。然后添加了一些条目。使用 getProperty() 方法检索并打印了一个值。然后我们获取了一个不存在的值,并依次打印了默认值。

package com.tutorialspoint;

import java.util.Properties;

public class PropertiesDemo {
   public static void main(String[] args) {
      Properties properties = new Properties();

      //populate properties object
      properties.put("1", "tutorials");
      properties.put("2", "point");
      properties.put("3", "is best");

      System.out.println("Properties elements: " + properties);
      System.out.println("Value: " + properties.getProperty("1"));
	  System.out.println("Using default value: " + properties.getProperty("4","Welcome"));
   }
}

输出

让我们编译并运行以上程序,这将产生以下结果。

Properties elements: {1=tutorials, 2=point, 3=is best}
Value: tutorials
Using default value: Welcome
java_util_properties.htm
广告

© . All rights reserved.