2010-03-08 62 views
4

將用戶消息存儲在配置文件中,然後在整個應用程序中檢索某些事件的最佳做法是什麼?存儲和檢索錯誤消息的最佳做法

我想具有條目,如

REQUIRED_FIELD = {0} is a required field 
INVALID_FORMAT = The format for {0} is {1} 

等1個一個配置文件,然後從一類稱他們會是這樣的

public class UIMessages { 
    public static final String REQUIRED_FIELD = "REQUIRED_FIELD"; 
    public static final String INVALID_FORMAT = "INVALID_FORMAT"; 

    static { 
     // load configuration file into a "Properties" object 
    } 
    public static String getMessage(String messageKey) { 
     // 
     return properties.getProperty(messageKey); 
    } 
} 

的這是正確的解決這個問題的方法,還是有一些事實上的標準已經到位?

回答

8

你正處在正確的軌道與消息放入屬性文件。如果你使用ResourceBundle,Java使得這很容易。您基本上創建一個屬性文件,其中包含您要支持的每個區域設置的消息字符串(messages_en.properties,messages_ja.properties),並將這些屬性文件捆綁到您的jar中。然後,在你的代碼,你提取消息:

ResourceBundle bundle = ResourceBundle.getBundle("messages"); 
String text = MessageFormat.format(bundle.getString("ERROR_MESSAGE"), args); 

當你加載包,Java將決定你在運行的區域設置並加載正確的消息。然後,您將您的參數與消息字符串一起傳入並創建本地化消息。

參考ResourceBundle

3

你的方法幾乎是正確的。我想添加一件事。如果您正在討論配置文件,最好有兩個.properties文件。

一個用於應用程序的默認配置。 (比方說defaultProperties.properties

其次爲用戶特定的配置(假設appProperties.properties

. . . 
// create and load default properties 
Properties defaultProps = new Properties(); 
FileInputStream in = new FileInputStream("defaultProperties"); 
defaultProps.load(in); 
in.close(); 

// create application properties with default 
Properties applicationProps = new Properties(defaultProps); 

// now load properties from last invocation 
in = new FileInputStream("appProperties"); 
applicationProps.load(in); 
in.close(); 
. . . 
相關問題