Java internationalization-use of resource packages

Source: Internet
Author: User
Tags locale setting

 
This article is a part of the chapter in j2se advanced edition, which is written by Jr. j2se advanced edition is in the writing and improvement stage. After reading, do you have any suggestions, criticism, please contact me, or in http://www.javaresearch.org/forum/thread.jsp? Column = 376 & Thread = 7576 'target = '_ blank' class = 'l2'> leave a message here. Thank you for reading this article.

In today's information society, especially with the emergence and popularization of the Internet, the distance between people is closer than ever before, and communication is also more frequent, the most fashionable concept nowadays is the Global Village. When I was a child, I only knew the village where I was born. People have to consider how to deal with people of different races and regions. This is true for people and our software. You need to consider how to make good use of your software for users in different parts of the world. Therefore, before each software starts, developers may need to consider the question of internationalization.

We know that Java can use the java. util. locale class to uniquely determine the combination of a specific language and country, that is, to abstract the end user's use environment. Meanwhile, some user-related information is placed in the resource package to dynamically obtain the final user display through the resource package. Resource packages can be implemented by resource files or resource subclasses.

Note: This article only intends to discuss the usage skills of resource packages during the internationalization process. For more information, please look forward to j2se advanced edition.

Resource Package

When writing an application, you need to deal with some information related to locale. For example, some static text on the page is expected to be displayed in a language that you are used. The most primitive approach is to hard encode the information into a program (which may be a large string of judgment statements), but in this way, the program code and variable Locale information are bundled together, if you need to modify the locale information or add other locale information, you have to modify the code again. The resource package can help you solve this problem. It puts the variable Locale information into the resource package to achieve the purpose of separating the two. The application can automatically obtain the required information from the corresponding resource package through the current locale settings. The concept of a resource package is similar to the resource file (RC file) used by Windows programmers ).

Generally, a resource package requires two functions: binding with a specific locale and reading information about locale.

Resourcebundle class

You can view the resource package as a big family composed of many Members (Child classes). Each member is associated with a different locale object. How does it complete the association function?

Each member in the resource package shares a name called base name, which is then extended according to certain naming rules. The names of some members are listed below:
Labelresources
Labelresources_de
Labelresources_de_ch
Labelresources_de_ch_unix
It can be seen that these sub-classes are based on the naming rules basename_policage_country_variant. The language and other variables are used when you construct the locale class. The resource package is associated with locale through the name that complies with the naming conventions. For example, labelresource_de_ch corresponds to the locale object composed of German (DE) and Swiss (Ch.

When your application needs to find the resource package associated with a specific locale object, it can call the getbundle method of resourcebundle and pass the locale object as a parameter.

  1. Locale currentlocale =NewLocale ("de", "ch", "Unix ");
  2. Resourcebundle myresources =
  3. Resourcebundle. getbundle ("labelresources", currentlocale );

If the resource package subclass matching the locale object cannot be found, getbundle will try to find the most matched subclass. The specific search policy is as follows: getbundle uses the base name, locale object and default locale to generate a sequence of candidate resource package names. If the language code, country code, and optional variables of a specific locale object are null, the base name is the unique candidate resource package name. Otherwise, the specific locale object (regionage1, country1 and variant1) and default locale (regionage2, country2 and variant2) will generate the following sequence:

  • Basename + "_" + language1 + "_" + country1 + "_" + variant1
  • Basename + "_" + language1 + "_" + country1
  • Basename + "_" + language1
  • Basename + "_" + language2 + "_" + country2 + "_" + variant2
  • Basename + "_" + language2 + "_" + country2
  • Basename + "_" + language2
  • Basename

Then, the getbundle method searches for matched resource package subclass in sequence based on the generated sequence and initializes the result subclass. First, it will look for a class that matches the name of the candidate resource package. If it finds a class that will create an instance of this class, we call it the result resource package. Otherwise, the getbundle method will find the corresponding resource file, which obtains the complete path of the resource file through the candidate resource package name ("Replace with"/"and add". properties). If a matching file is found, the getbundle method uses the resource file to create a propertyresourcebundle instance, that is, the final result resource package. At the same time, the getbundle method caches these resource package instances for future use.

If no result resource package is found, this method throws a missingresourceexception. Therefore, to prevent exceptions from being thrown, at least one base name resource package subclass is required.

Note: The base name parameter must be a complete Class Name (such as labelresources and resource. labelresources), which is equivalent to specifying the complete class path when you reference a class. However, to be compatible with previous versions, you can use "/" to replace "." To indicate paths when using propertyresourcebundles.

For example, you have the following resource classes and resource files: myresources. Class, myresources_fr_ch.properties, myresources_fr_ch.class, myresources_fr.properties, myresources_en.properties, and myresources_es_es.class. You use the following locale settings to call the getbundle method. You will get different result Resource Packages (assuming that the default locale is locale ("en", "UK ")), for more information, see Table 13.4.
Table 13.4 locale settings and result resource package
Locale setting result resource package
Locale ("FR", "ch") myresources_fr_ch.class
Locale ("FR", "FR") myresources_fr.properties
Locale ("de", "de") myresources_en.properties
Locale ("en", "us") myresources_en.properties
Locale ("es", "es") myresources_es_es.class

After creating a resource package subclass instance, You need to obtain the specific information. The information is stored as a key-value pair in the resource package. Table 13.5 lists the content of the labelresources. properties file.

Table 13.5 labelresources. Properties

  1. # This is labelresources. properties File
  2. Greetings = hello!
  3. Farewell = goodbye.
  4. Inquiry = Hello?

The string on the left of the equal sign indicates the primary key, which is unique. To obtain the value corresponding to the primary key, you can call the getstring method of the resourcebundle class and use the primary key as the parameter. In addition, lines starting with "#" in the file represent comment rows.

Listresourcebundle and propertyresourcebundle subclasses

Abstract class resourcebundle has two subclasses: listresourcebundle and propertyresourcebundle. They indicate two different implementation methods for the resource package subclass.

Propertyresourcebundle is used together with the resource file. An Attribute file is a common text file. You only need to write resource files with different names for different locale settings. However, a resource file can only contain strings. To store other types of objects, you can use listresourcebundle.

Listresourcebundle stores the key-Value Pair information in the list of classes, and you must implement a specific subclass of listresourcebundle.

If listresourcebundle and propertyresourcebundle cannot meet your needs, you can implement your own resourcebundle subclass. Your subclass must cover two methods: handlegetobject and getkeys.

Use resource files

The simplest way to use a resource package is to use the resource file. The following steps are generally required to use the resource file:
1. Create a default resource file
To prevent the resource file from being located, you 'd better implement a default resource file. The file name is the base name of the resource package plus the. properties suffix.
2. Create the required resource file
Prepare the corresponding resource file for the supported locale settings.
3. Set locale
You must provide the locale setting or switching function somewhere in the program, or put it in the configuration file.
4. Create a resource package based on locale settings
Resourcebundle resource =
Resourcebundle. getbundle ("labelbundle", currentlocale );
5. Obtain Locale information through the resource package
String value = resource. getstring ("welcome ");

Note: when using the base name, pay special attention to the complete Class Name (or path name). For example, the class package of your application is Org. javaresearch. j2seimproved. i18n, and your resource file is in the resource subdirectory of your application, your base name should be Org. javaresearch. j2seimproved. i18n. resource. labelbundlebundle instead of resource. labelbundlebundle.

Use listresourcebundle

The steps for using listresourcebundle are basically the same as those for using resource files, except that you need to replace the corresponding resource files with the listresourcebundle subclass. For example, if the base name of your application is labelbundle and you want to support locale ("en", "us") and locale ("ZH", "cn "), you need to provide the following java files. Pay attention to the correspondence between class names and locale.
Labelbundle_en_us.java
Labelbundle_zh_cn.java
Labelbundle. Java (default class)

Code 13.3 lists the source code of labelbundle_zh_cn.java. Compared with the "Key = value" method in the resource file, in this file, you first use a key-value pair to initialize a two-dimensional array, and return the array in the getcontents method.

Sample Code 13.3: labelbundle_zh_cn.java

  1. PackageOrg. javaresearch. j2seimproved. i18n;Import
  2. Java. util.Listresourcebundle;
  3. Public ClassLabelbundle_zh_cnExtendsListresourcebundle {
  4. Public Object[] [] Getcontents (){
  5. ReturnContents;
  6. }
  7. Private Object[] [] Contents = {
  8. {"Title", "title "},
  9. {"Surname", "surname "},
  10. {"Firstname", "name "},
  11. };
  12. }

After creating a resource class, you also need to set locale and create a resource package based on locale. You cannot use the getstring method when getting a specific value through the resource package. Instead, you should call the GetObject method. Because the GetObject method returns an object, you also need to perform correct type conversion. In fact, we recommend that you call the GetObject method instead of the getstring method when using resource files for your program's versatility.

  1. StringTitle = (String) Resource. GetObject ("title ");

For detailed use of listresourcebundle, refer to the listresourcebundlesample. Java program in the internationalization section of the Code attached to this book.

Messageformat class

We have discussed how to use resource files to separate code and variable information. However, in the actual process, some information cannot be fully defined in advance, and some running results may be used. The most typical example is the error prompt code, for example, the system prompts that an input must be within a certain range. Using the resource file mentioned above does not solve this problem well, so the messageformat class is introduced in Java.

Messageformat provides a language-independent way to assemble messages. It allows you to replace a part of the message string with a specified parameter at runtime. You can define a pattern for messageformat, in which you can use placeholders to represent the changed part. For example, you have the following sentence:

Hello, peachpi! Welcome to the Java Research Organization website! The current time is 2003-8-1 16:43:12.

The ITALIC underlined part is changeable. You need to determine the final display based on the current time and different login users. We use placeholders to represent the changed parts. We can see the following pattern:

Hello, {0 }! Welcome to the Java Research Organization website! The current time is: {1, date} {1, time }.

The placeholder format is {argumentindex, formattype, formatstyle}. For details, refer to the messageformat API instructions. Here we define two placeholders. The numbers correspond to the indexes in the input parameter array, the {0} placeholder is replaced by the first parameter, and the {1} placeholder is replaced by the second parameter, and so on.
You can set up to 10 placeholders. Each placeholder can appear multiple times and in different formats, such as {1, date} and {1, time }. By placing these schema definitions in different resource files, you can get different schema definitions based on different locale settings and dynamically replace placeholders with parameters.

Next we will take the messageformatsample. Java program (for the source file, see the code attached to this book) as an example to illustrate each step in detail.
1. Find the variable part and define the mode accordingly. Put the mode into different resource files.
For example, the following two resource files are defined for the above mode:
Messagesbundle_en_us.properties
Welcome = Hi, {0 }! Welcome to Java research organization!
Messagesbundle_zh_cn.properties
Welcome = Hello, {0 }! Welcome to the Java Research Organization website!

2. Create a messageformat object and set its locale attribute.

  1. Messageformat formatter =NewMessageformat ("");
  2. Formatter. setlocale (currentlocale );

3. Get the mode definition from the resource package and set parameters.

  1. Messages = resourcebundle. getbundle (
  2. "Org. javaresearch. j2seimproved. i18n. Resource. messagesbundle", currentlocale );
  3. Object[] Testargs = {"peachpi ",NewDate ()};

4. format the schema definition and parameters.

  1. System. Out. println (formatter. Format (messages. getstring ("welcome"), testargs ));

About resource package Organization

Generally, you organize resource packages based on the purpose of resources. For example, you will put all the page buttons in a resource package named buttonresources. In actual application, the following principles help you decide how to organize resource packages:
1. easy to maintain.
2. It is best not to put all the information into a resource package, because it will take a lot of time to load the resource package into the memory.
3. It is best to divide a large resource package into several small resource packages so that necessary resources can be imported during use to reduce memory consumption.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.