search
HomeJavajavaTutorialHow to use the internationalized underlying class ResourceBundle in Java

    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:亿速云. If there is any infringement, please contact admin@php.cn delete
    带你搞懂Java结构化数据处理开源库SPL带你搞懂Java结构化数据处理开源库SPLMay 24, 2022 pm 01:34 PM

    本篇文章给大家带来了关于java的相关知识,其中主要介绍了关于结构化数据处理开源库SPL的相关问题,下面就一起来看一下java下理想的结构化数据处理类库,希望对大家有帮助。

    Java集合框架之PriorityQueue优先级队列Java集合框架之PriorityQueue优先级队列Jun 09, 2022 am 11:47 AM

    本篇文章给大家带来了关于java的相关知识,其中主要介绍了关于PriorityQueue优先级队列的相关知识,Java集合框架中提供了PriorityQueue和PriorityBlockingQueue两种类型的优先级队列,PriorityQueue是线程不安全的,PriorityBlockingQueue是线程安全的,下面一起来看一下,希望对大家有帮助。

    完全掌握Java锁(图文解析)完全掌握Java锁(图文解析)Jun 14, 2022 am 11:47 AM

    本篇文章给大家带来了关于java的相关知识,其中主要介绍了关于java锁的相关问题,包括了独占锁、悲观锁、乐观锁、共享锁等等内容,下面一起来看一下,希望对大家有帮助。

    一起聊聊Java多线程之线程安全问题一起聊聊Java多线程之线程安全问题Apr 21, 2022 pm 06:17 PM

    本篇文章给大家带来了关于java的相关知识,其中主要介绍了关于多线程的相关问题,包括了线程安装、线程加锁与线程不安全的原因、线程安全的标准类等等内容,希望对大家有帮助。

    Java基础归纳之枚举Java基础归纳之枚举May 26, 2022 am 11:50 AM

    本篇文章给大家带来了关于java的相关知识,其中主要介绍了关于枚举的相关问题,包括了枚举的基本操作、集合类对枚举的支持等等内容,下面一起来看一下,希望对大家有帮助。

    详细解析Java的this和super关键字详细解析Java的this和super关键字Apr 30, 2022 am 09:00 AM

    本篇文章给大家带来了关于Java的相关知识,其中主要介绍了关于关键字中this和super的相关问题,以及他们的一些区别,下面一起来看一下,希望对大家有帮助。

    java中封装是什么java中封装是什么May 16, 2019 pm 06:08 PM

    封装是一种信息隐藏技术,是指一种将抽象性函式接口的实现细节部分包装、隐藏起来的方法;封装可以被认为是一个保护屏障,防止指定类的代码和数据被外部类定义的代码随机访问。封装可以通过关键字private,protected和public实现。

    Java数据结构之AVL树详解Java数据结构之AVL树详解Jun 01, 2022 am 11:39 AM

    本篇文章给大家带来了关于java的相关知识,其中主要介绍了关于平衡二叉树(AVL树)的相关知识,AVL树本质上是带了平衡功能的二叉查找树,下面一起来看一下,希望对大家有帮助。

    See all articles

    Hot AI Tools

    Undresser.AI Undress

    Undresser.AI Undress

    AI-powered app for creating realistic nude photos

    AI Clothes Remover

    AI Clothes Remover

    Online AI tool for removing clothes from photos.

    Undress AI Tool

    Undress AI Tool

    Undress images for free

    Clothoff.io

    Clothoff.io

    AI clothes remover

    AI Hentai Generator

    AI Hentai Generator

    Generate AI Hentai for free.

    Hot Tools

    SublimeText3 English version

    SublimeText3 English version

    Recommended: Win version, supports code prompts!

    SAP NetWeaver Server Adapter for Eclipse

    SAP NetWeaver Server Adapter for Eclipse

    Integrate Eclipse with SAP NetWeaver application server.

    WebStorm Mac version

    WebStorm Mac version

    Useful JavaScript development tools

    SublimeText3 Linux new version

    SublimeText3 Linux new version

    SublimeText3 Linux latest version

    MinGW - Minimalist GNU for Windows

    MinGW - Minimalist GNU for Windows

    This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.