Java ResourceBundle getString() 方法



描述

Java ResourceBundle getString(String key) 方法從該資源包或其父資源包中獲取給定鍵的字串。

宣告

以下是java.util.ResourceBundle.getString() 方法的宣告

public final String getString(String key)

引數

key − 所需字串的鍵

返回值

此方法返回給定鍵的字串。

異常

  • NullPointerException − 如果 key 為 null

  • MissingResourceException − 如果找不到給定鍵的物件

  • ClassCastException − 如果為給定鍵找到的物件不是字串

從美國區域設定的屬性檔案中獲取作為字串的值

以下示例演示了 Java ResourceBundle getString() 方法的使用,用於根據鍵獲取物件。我們為對應的 hello_en_US.properties 檔案建立了一個美國區域設定的資源包。然後,我們使用 getString() 獲取分配給鍵 hello 的文字並將其打印出來。

package com.tutorialspoint;

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"));
   }
}

輸出

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

hello = Hello World!

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

Hello World!

從法國區域設定的屬性檔案中獲取作為字串的值

以下示例演示了 Java ResourceBundle getString() 方法的使用,用於根據鍵獲取物件。我們為對應的 hello_fr_FR.properties 檔案建立了一個法國區域設定的資源包。然後,我們使用 getString() 獲取分配給鍵 hello 的文字並將其打印出來。

package com.tutorialspoint;

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.FRANCE);

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

輸出

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

hello = Bonjour le monde!

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

Bonjour le monde!

從德國區域設定的屬性檔案中獲取作為字串的值

以下示例演示了 Java ResourceBundle getString() 方法的使用,用於根據鍵獲取物件。我們為對應的 hello_de_DE.properties 檔案建立了一個德國區域設定的資源包。然後,我們使用 getString() 獲取分配給鍵 hello 的文字並將其打印出來。

package com.tutorialspoint;

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.GERMANY);

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

輸出

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

hello = Hallo Welt!

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

Hallo Welt!
java_util_resourcebundle.htm
廣告
© . All rights reserved.