Table of Contents
1. Prepare resource files
2. Loading resource files
3. Get the localized string
4. Tips for using ResourceBundle
4.1 Choose the appropriate resource file format
4.2 Processing special characters in localized strings
4.3 Handling missing localized strings
4.4 Handling dynamic localization strings
4.5 处理多个资源文件
4.6 自定义资源加载器
4.7 动态更新资源文件
Home Java javaTutorial How to use the internationalized underlying class ResourceBundle in Java

How to use the internationalized underlying class ResourceBundle in Java

May 04, 2023 pm 02:22 PM
java resourcebundle

    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
    Copy after login

    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
    Copy after login

    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());
    Copy after login

    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);
    Copy after login

    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");
    Copy after login

    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.
    Copy after login

    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);
    Copy after login

    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
    Copy after login

    在这个示例中,我们使用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
    Copy after login

    在这个示例中,我们定义了一个名为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
    Copy after login

    在这个示例中,我们首先使用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 of this Website
    The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

    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

    Notepad++7.3.1

    Notepad++7.3.1

    Easy-to-use and free code editor

    SublimeText3 Chinese version

    SublimeText3 Chinese version

    Chinese version, very easy to use

    Zend Studio 13.0.1

    Zend Studio 13.0.1

    Powerful PHP integrated development environment

    Dreamweaver CS6

    Dreamweaver CS6

    Visual web development tools

    SublimeText3 Mac version

    SublimeText3 Mac version

    God-level code editing software (SublimeText3)

    Perfect Number in Java Perfect Number in Java Aug 30, 2024 pm 04:28 PM

    Guide to Perfect Number in Java. Here we discuss the Definition, How to check Perfect number in Java?, examples with code implementation.

    Weka in Java Weka in Java Aug 30, 2024 pm 04:28 PM

    Guide to Weka in Java. Here we discuss the Introduction, how to use weka java, the type of platform, and advantages with examples.

    Smith Number in Java Smith Number in Java Aug 30, 2024 pm 04:28 PM

    Guide to Smith Number in Java. Here we discuss the Definition, How to check smith number in Java? example with code implementation.

    Java Spring Interview Questions Java Spring Interview Questions Aug 30, 2024 pm 04:29 PM

    In this article, we have kept the most asked Java Spring Interview Questions with their detailed answers. So that you can crack the interview.

    Break or return from Java 8 stream forEach? Break or return from Java 8 stream forEach? Feb 07, 2025 pm 12:09 PM

    Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

    TimeStamp to Date in Java TimeStamp to Date in Java Aug 30, 2024 pm 04:28 PM

    Guide to TimeStamp to Date in Java. Here we also discuss the introduction and how to convert timestamp to date in java along with examples.

    Java Program to Find the Volume of Capsule Java Program to Find the Volume of Capsule Feb 07, 2025 am 11:37 AM

    Capsules are three-dimensional geometric figures, composed of a cylinder and a hemisphere at both ends. The volume of the capsule can be calculated by adding the volume of the cylinder and the volume of the hemisphere at both ends. This tutorial will discuss how to calculate the volume of a given capsule in Java using different methods. Capsule volume formula The formula for capsule volume is as follows: Capsule volume = Cylindrical volume Volume Two hemisphere volume in, r: The radius of the hemisphere. h: The height of the cylinder (excluding the hemisphere). Example 1 enter Radius = 5 units Height = 10 units Output Volume = 1570.8 cubic units explain Calculate volume using formula: Volume = π × r2 × h (4

    Create the Future: Java Programming for Absolute Beginners Create the Future: Java Programming for Absolute Beginners Oct 13, 2024 pm 01:32 PM

    Java is a popular programming language that can be learned by both beginners and experienced developers. This tutorial starts with basic concepts and progresses through advanced topics. After installing the Java Development Kit, you can practice programming by creating a simple "Hello, World!" program. After you understand the code, use the command prompt to compile and run the program, and "Hello, World!" will be output on the console. Learning Java starts your programming journey, and as your mastery deepens, you can create more complex applications.

    See all articles