2010-03-08 60 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(); 
. . . 
相关问题