Java中使用資源包儲存和訪問在應用程序中要使用到的本地特定資源對象。

一個本地特定資源的最簡單例子就是字符串對象。舉例來說,在下面的應用程序中,要求輸出不同的消息,而這些消息取決于在命令行中的本地指定。我們用靜態的方法來創建一個資源包的實例:

java.util.ResourceBundle.getBundle():
ResourceBundle messages = ResourceBundle.getBundle("messages", Locale.ENGLISH);

其中getBundle()方法有三種方式來讓你選擇一個特定的locale和classloader,或者你可選擇默認項來選擇默認的locale和classloarder。

正如你在前面看到的那段代碼,得到一個資源包的實例并沒有什么實際價值。因為例子代碼locale使用英語表示的,所以在執行上面這個方法的時候,ResourceBundle 就會從應用程序的classpath中尋找名為“messages_en.properties”的文件。如果沒有找到此文件,那么就會出現java.util.MissingResourceException這樣一個錯誤提示。

在實際的應用程序中,你可以根據用戶設定或是系統設定來選擇你的locale。下面是一個根據啟動時的設定來選擇locale的例子:

Locale locale = Locale.ENGLISH;
         if ( args.length != 0 ) {
     locale = new Locale(args[0]);
}
ResourceBundle messages = ResourceBundle.getBundle("messages", locale);

在有了資源包的實例后,就可以調用一種get方式來獲得你想要的本地資源。

ResourceBundle類型定義了獲得字符串、字符串數組和獲得對象的方法。在這個例子中,一個字符串形式的“welcome.message”將被觸發:

String message = messages.getString("welcome.message");

當調用getString()函數的時候,ResourceBundle就從先前得到的工具文件中尋找有關鍵字名“welcome.message”的字符串對象。如果沒有找到關鍵字,那么就會出現java.util.MissingResourceException錯誤提示。

其中用到的道具文件就如下面這種形式:

messages_en.properties:
welcome.message=Welcome to fantastic application and thanks for choosing
Acme, Inc.

messages_de.properties
welcome.message=Heißen Sie willkommen zu phantastischer Anwendung und Dank zum
Wählen von Gipfel, Inc.

messages_fr.properties:
welcome.message=Bienvenu a l'application fantastique et remercie pour choisir
de Point Culminant, Inc.

(請注意,上面的內容是我們用自動翻譯工具翻譯成法語和德語的。)

除了字符串以外,你還可以對其他對象使用資源包。例如,你可以創建你自己的獨立于道具文件的資源包實例。不管你是需要儲存本地特定字符串還是需要處理其他更復雜的對象,資源包都能為你提供很好的選擇。

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

public class ResourceBundleTip {
     public static void main(String[] args) {
         Locale locale = Locale.ENGLISH;
        
         if ( args.length != 0 ) {
             locale = new Locale(args[0]);
         }
        
         ResourceBundle messages = ResourceBundle.getBundle("messages", locale);
         String message = messages.getString("welcome.message");
        
         System.out.println(message);    
     }
}