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.