Java System getProperty() 方法



描述

Java System getProperty(String key) 方法獲取由指定key指示的系統屬性。

宣告

以下是java.lang.System.getProperty() 方法的宣告

public static String getProperty(String key)

引數

key − 這是系統屬性的名稱。

返回值

此方法返回系統屬性的字串值,如果不存在具有該鍵的屬性,則返回 null。

異常

  • SecurityException − 如果存在安全管理器,並且其 checkPropertyAccess 方法不允許訪問指定的系統屬性。

  • NullPointerException − 如果 key 為 null。

  • IllegalArgumentException − 如果 key 為空。

示例:獲取使用者目錄

以下示例演示了 java.lang.System.getProperty() 方法的使用。在這個程式中,我們使用 getProperty() 方法並傳入 "user.dir" 來檢索並列印使用者目錄。在下一條語句中,我們傳入一個不存在的鍵來檢查 getProperty() 方法是否返回 null。

package com.tutorialspoint;

public class SystemDemo {

   public static void main(String[] args) {

      // prints the name of the system property
      System.out.println(System.getProperty("user.dir"));

      // prints null if system property is not present
      System.out.println(System.getProperty("user.name1"));
   }
} 

輸出

讓我們編譯並執行上面的程式,這將產生以下結果:

C:\Users\Tutorialspoint\eclipse-workspace\Tutorialspoint
null

示例:獲取作業系統名稱

以下示例演示了 java.lang.System.getProperty() 方法的使用。在這個程式中,我們使用 getProperty() 方法並傳入 "os.name" 來檢索並列印使用者目錄。

package com.tutorialspoint;

public class SystemDemo {

   public static void main(String[] args) {
   
      // prints the name of the Operating System
      System.out.println(System.getProperty("os.name"));
   }
} 

輸出

讓我們編譯並執行上面的程式,這將產生以下結果:

Windows 11

示例:獲取 Java 執行時詳細資訊

以下示例演示了 java.lang.System.getProperty() 方法的使用。在這個程式中,我們使用 getProperty() 方法並傳入 "java.runtime.version" 來檢索並列印使用者目錄。

package com.tutorialspoint;

public class SystemDemo {

   public static void main(String[] args) {

      // prints Java Runtime Version
      System.out.println(System.getProperty("java.runtime.version" ));
   }
} 

輸出

讓我們編譯並執行上面的程式,這將產生以下結果:

21.0.2+13-LTS-58
java_lang_system.htm
廣告
© . All rights reserved.