Java ResourceBundle 類



簡介

Java ResourceBundle 類包含特定於區域設定的物件。以下是關於 ResourceBundle 的重要要點:

  • 此類允許您編寫易於本地化或翻譯成不同語言的程式。

  • 此類程式可以輕鬆地處理多個區域設定,並可以稍後輕鬆修改以支援更多區域設定。

  • Java 平臺提供了 ResourceBundle 的兩個子類,ListResourceBundle 和 PropertyResourceBundle。

類宣告

以下是 java.util.ResourceBundle 類的宣告:

public abstract class ResourceBundle
   extends Object

欄位

以下是 java.util.ResourceBundle 類的欄位:

protected ResourceBundle parent - 這是此捆綁包的父捆綁包。

類建構函式

序號 建構函式和描述
1

ResourceBundle()

這是唯一的建構函式。

類方法

序號 方法和描述
1 static void clearCache()

此方法從使用呼叫方類載入器載入的快取中刪除所有資源包。

2 boolean containsKey(String key)

此方法確定此 ResourceBundle 或其父捆綁包中是否包含給定的鍵。

3 static ResourceBundle getBundle(String baseName)

此方法使用指定的基名稱、預設區域設定和呼叫方類載入器獲取資源包。

4 abstract Enumeration<String> getKeys()

此方法返回鍵的列舉。

5 Locale getLocale()

此方法返回此資源包的區域設定。

6 Object getObject(String key)

此方法從此資源包或其父級之一獲取給定鍵的物件。

7 String getString(String key)

此方法從此資源包或其父級之一獲取給定鍵的字串。

8 String[] getStringArray(String key)

此方法從此資源包或其父級之一獲取給定鍵的字串陣列。

9 protected abstract Object handleGetObject(String key)

此方法從此資源包獲取給定鍵的物件。

10 protected Set<String> handleKeySet()

此方法查詢給定日期在此時區中是否處於夏令時。

11 Set<String> keySet()

此方法返回此 ResourceBundle 及其父捆綁包中包含的所有鍵的 Set。

12 protected void setParent(ResourceBundle parent)

此方法設定此捆綁包的父捆綁包。

繼承的方法

此類繼承自以下類的方法:

  • java.util.Object

獲取 ResourceBundle 鍵的示例

以下示例演示瞭如何使用 Java ResourceBundle getKeys() 方法列印屬性檔案中存在的鍵列表。我們為相應的 hello_en_US.properties 檔案建立了一個 US Locale 的資源包。然後我們列印分配給鍵 hello 的文字。然後使用 getKeys() 方法檢索鍵的列舉並列印鍵。

package com.tutorialspoint;

import java.util.Enumeration;
import java.util.Locale;
import java.util.ResourceBundle;

public class ResourceBundleDemo {
   public static void main(String[] args) {

      // create a new ResourceBundle with specified locale
      ResourceBundle bundle = ResourceBundle.getBundle("hello", Locale.US);

      // print the text assigned to key "hello"
      System.out.println("" + bundle.getString("hello"));

      // get the keys
      Enumeration<String> enumeration = bundle.getKeys();

      // print all the keys
      while (enumeration.hasMoreElements()) {
         System.out.println("" + enumeration.nextElement());
      }
   }
}

輸出

假設我們在你的 CLASSPATH 中有一個可用的資原始檔 hello_en_US.properties,內容如下。此檔案將用作我們示例程式的輸入:

hello = Hello World!
bye = Goodbye World!
morning = Good Morning World!
廣告