Home  >  Article  >  Java  >  How to use the internationalized underlying class ResourceBundle in Java

How to use the internationalized underlying class ResourceBundle in Java

PHPz
PHPzforward
2023-05-04 14:22:06942browse

    In Java development, ResourceBundle is a mechanism to conveniently manage localized resources. It allows the program to automatically load the corresponding localized resource files according to the language and country/region of the current system environment, thereby avoiding hard coding and reducing repeated code. The following are the basic steps for using ResourceBundle:

    1. Prepare resource files

    ResourceBundle implements localization by loading resource files, so a corresponding resource needs to be prepared for each language and country/region document. Resource files can be text files in .properties format, or .class files or .jar files.

    In the resource file, you need to specify an attribute name for each string that needs to be localized, and then provide a translation in the language for each attribute name. For example, here is an example of a resource file named messages.properties:

    greeting=Hello
    farewell=Goodbye

    Different translations can be provided for the same property name in different languages ​​and countries. For example, the following is an example of a French resource file named messages_fr.properties:

    greeting=Bonjour
    farewell=Au revoir

    2. Loading resource files

    In Java, you can use the ResourceBundle class to load resource files. The ResourceBundle class provides several different constructors to load resource files, for example:

    ResourceBundle rb = ResourceBundle.getBundle("messages", Locale.getDefault());

    This statement will load the resource file named messages according to the default language and country/region of the current system environment. If the system environment is English and the United States, then this statement will load the messages.properties resource file. If the system environment is French and French, then this statement will load the messages_fr.properties resource file.

    If you need to load resource files in a specified language and country/region, you can use the getBundle() method with the Locale parameter. For example:

    Locale locale = new Locale("fr", "FR");
    ResourceBundle rb = ResourceBundle.getBundle("messages", locale);

    This statement will load the French/French resource file named messages_fr_FR.properties.

    3. Get the localized string

    Once the resource file is successfully loaded, you can use the getString() method of ResourceBundle to obtain the localized string. For example:

    String greeting = rb.getString("greeting");
    String farewell = rb.getString("farewell");

    These statements will obtain the localized strings with attributes named greeting and farewell from the resource file, and assign them to the greeting and farewell variables respectively. If the specified property name cannot be found, the getString() method will throw a MissingResourceException.

    4. Tips for using ResourceBundle

    In addition to the above basic steps, there are some noteworthy features and tips for using ResourceBundle:

    4.1 Choose the appropriate resource file format

    ResourceBundle supports multiple resource file formats, including .properties, .xml and .class files, etc. For simple localized strings, the .properties format is often the most common choice because it is simple to use, easy to edit and localize.

    For more complex localized resources, such as images, sounds, videos, etc., you may need to use resource files in other formats. For example, you can use .class files or .jar files to include image or sound files and use the ResourceBundle's ClassLoader.getSystemClassLoader() method to load these files.

    4.2 Processing special characters in localized strings

    Localized strings may contain various special characters, such as newlines, tabs, Unicode characters, etc. If you embed these characters directly into resource files, it may cause unnecessary trouble and errors.

    In order to avoid these problems, you can use Java escape characters to represent these special characters. For example, you can use "\n" to represent a newline character, "\t" to represent a tab character, "\uXXXX" to represent Unicode characters, etc.

    4.3 Handling missing localized strings

    In some cases, there may be situations where translations are not provided for localized strings in certain languages. In order to avoid MissingResourceException exceptions in the program, you can provide a default translation for these missing strings in the resource file, such as English translation. For example, the following is an example of a messages_fr.properties file with default translation:

    greeting=Bonjour
    farewell=Au revoir
    warning=Attention: This message has no translation in French. Please refer to the English version.

    In this way, in the French environment, if the localized string for a certain property name cannot be found, the ResourceBundle will automatically return the Default translation of attribute names, thus avoiding program exceptions.

    4.4 Handling dynamic localization strings

    Some localization strings may contain dynamic content, such as time, date, numbers, currency, etc. In order to localize these strings correctly, you need to use Java's formatting mechanisms, such as MessageFormat and NumberFormat, etc. For example, the following is an example of using MessageFormat to localize a dynamic string:

    String pattern = rb.getString("greeting");
    Object[] arguments = {"John"};
    String greeting = MessageFormat.format(pattern, arguments);

    In this example, pattern is a localized string containing the placeholder "{0}", "{0}" Represents the location that needs to be replaced with dynamic content. arguments is an array containing the actual dynamic content, which will replace the positions of "{0}" in order. Finally, the MessageFormat.format() method returns a localized string.

    4.5 处理多个资源文件

    在一些情况下,可能需要使用多个资源文件来管理不同类型或不同用途的本地化资源。在这种情况下,可以使用ResourceBundle.Control类的方法来指定资源文件的搜索路径和加载顺序。

    例如,可以使用ResourceBundle.Control.getControl()方法来获取默认的ResourceBundle.Control实例,然后使用ResourceBundle.getBundle()方法来指定基础名称和Locale信息,以便查找合适的资源文件。例如,以下是一个使用多个资源文件来管理本地化字符串的示例:

    ResourceBundle.Control control = ResourceBundle.Control.getControl(ResourceBundle.Control.FORMAT_PROPERTIES);
    ResourceBundle messages = ResourceBundle.getBundle("Messages", new Locale("fr"), control);
    ResourceBundle errors = ResourceBundle.getBundle("Errors", new Locale("fr"), control);
    
    String greeting = messages.getString("greeting");
    String error = errors.getString("invalid_input");
    
    System.out.println(greeting); // Bonjour
    System.out.println(error); // Entrée invalide

    在这个示例中,我们使用ResourceBundle.Control.FORMAT_PROPERTIES指定了资源文件的格式为.properties文件,然后分别使用Messages和Errors作为基础名称来获取不同类型的资源文件。这样,我们就可以轻松地管理不同类型的本地化资源,从而使程序更加可读和易于维护。

    4.6 自定义资源加载器

    如果默认的资源加载机制无法满足需求,我们还可以自定义资源加载器来实现更高级的功能。自定义资源加载器需要继承java.util.ResourceBundle.Control类,并重写其中的方法来实现自定义逻辑。

    例如,以下是一个使用自定义资源加载器来加载本地化字符串的示例:

    public class MyResourceLoader extends ResourceBundle.Control {
        @Override
        public ResourceBundle newBundle(String baseName, Locale locale, String format, ClassLoader loader, boolean reload)
                throws IllegalAccessException, InstantiationException, IOException {
            String bundleName = toBundleName(baseName, locale);
            String resourceName = toResourceName(bundleName, "myproperties");
            InputStream stream = loader.getResourceAsStream(resourceName);
            if (stream != null) {
                try {
                    return new PropertyResourceBundle(stream);
                } finally {
                    stream.close();
                }
            } else {
                return super.newBundle(baseName, locale, format, loader, reload);
            }
        }
    }
    
    ResourceBundle.Control control = new MyResourceLoader();
    ResourceBundle messages = ResourceBundle.getBundle("Messages", new Locale("fr"), control);
    
    String greeting = messages.getString("greeting");
    
    System.out.println(greeting); // Bonjour

    在这个示例中,我们定义了一个名为MyResourceLoader的自定义资源加载器,并重写了其中的newBundle()方法来实现自定义资源加载逻辑。然后,我们使用这个自定义资源加载器来获取Messages资源文件中的本地化字符串。这样,我们就可以实现更高级的资源加载功能,从而满足更复杂的需求。

    4.7 动态更新资源文件

    有时候,在应用程序运行期间,可能需要动态地更新资源文件中的某些值。在Java中,我们可以使用PropertyResourceBundle类来实现这个功能。

    PropertyResourceBundle是ResourceBundle的一个子类,它可以读取.properties格式的资源文件,并将其转换为一个键值对的形式。然后,我们可以通过这个键值对来动态地更新资源文件中的值。

    例如,以下是一个使用PropertyResourceBundle来动态更新本地化字符串的示例:

    // 加载资源文件
    InputStream stream = new FileInputStream("Messages.properties");
    PropertyResourceBundle bundle = new PropertyResourceBundle(stream);
    
    // 动态更新本地化字符串
    bundle.handleKey("greeting", (key, value) -> "Hello");
    
    // 输出本地化字符串
    String greeting = bundle.getString("greeting");
    System.out.println(greeting); // Hello

    在这个示例中,我们首先使用FileInputStream来加载Messages.properties资源文件,然后将其转换为一个PropertyResourceBundle对象。然后,我们使用handleKey()方法来动态地更新greeting这个键对应的值。最后,我们使用getString()方法来获取更新后的本地化字符串。

    这种动态更新资源文件的方式可以使应用程序更加灵活,能够快速响应变化。但是需要注意的是,这种方式需要保证资源文件的正确性和一致性,否则可能会导致应用程序运行出错。

    The above is the detailed content of How to use the internationalized underlying class ResourceBundle in Java. For more information, please follow other related articles on the PHP Chinese website!

    Statement:
    This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete