Java Common class Libraries-internationalized programs (Locale,resourcebundle and Messageformat processing dynamic text)

Source: Internet
Author: User
Tags locale string format

This chapter aimsMaster the basic Realization principle of internationalization procedure. Master the role of resource files. Master the basic implementation principle of the locale class. Mastering the role of the ResourceBundle class. you can use Messageformat to handle dynamic text. understand the use of resource classes. Internationalization ProgramThe operation of internationalization refers to a program can adapt to multiple languages at the same time, that is: if the user of the program is Chinese, it will be displayed in Chinese language, if the current program is the British people, will be in English as the display text, that is, can be internationalized operation, Adapt a program to the language requirements of each country. so for each country, the code for each program will not change, but only the text that it displays is different. the implementation of the Internationalization program ideas:
The program finds different resource files according to different language environment, then extracts the contents from the resource files, the contents of the resource files are saved in the form of key-value, so the corresponding value can be found by its key when reading. support classes for internationalization implementationsif you want to implement the internationalization of a Java program, you must complete the following three classes:Java.util.Locale: The language class used to represent a country. java.util.ResourceBundle: Used to access resource files. Java.util.MessageFormat: A placeholder string that formats the resource file. Locale Classlocale represents a local, in fact, an ISO-encoded encapsulation class is used. For each country there is a unique encoding, which is called the ISO encoding, and locale can be used to specify a specific country code. For example:China's code: ZH-CNEnglish-American code: en-UScode for French: Fr-frResourceBundleThis class is specialized to complete the property file read operations, read directly specify the file name (this file name does not need to specify a suffix, the suffix is unified *.properties), you can automatically select the required resource files according to locale code specified by locale. Public Static final ResourceBundle getbundle (String baseName), this method is the resource file for the specified operation, and this method finds the default operating system's language locale object. Public Static final ResourceBundle getbundle (String baseName, locale locale), which is also the resource file for the specified operation, and passes in the Locale object. Public Final string getString (string key) obtains the corresponding value based on key. The following is a program to observe the use of resource files, and how to use ResourceBundle to read resource files. it is best to capitalize the first letter of the word when the resource file is named. message.properties:
Info=111hello

where info is what you need in your program, and hello is the specific content that this info points to.To read data from the resource file:
Import Java.util.ResourceBundle;p ublic class interdemo01{public static void Main (String args[]) {ResourceBundle RB = Reso Urcebundle.getbundle ("Message");//Locate the resource file without writing the suffix System.out.println ("content:" + rb.getstring ("info"));//get content from the resource file}};


implementation of Java internationalization programafter understanding the ResourceBundle class and resource files, the following is a combination of locale classes to complete the development of internationalized programs. Development Requirements:can export different countries according to different countries "Hello"English: Hello!English: hello!French: bonjour!define different resource files separately, you need to define three resource files at this time, and specify the language code corresponding to the resource file when you define the resource file:English: Message_zh_cn.propertiesEnglish: Message_en_us.propertiesFrench: Message_fr_fr.propertiesmessage_zh_cn.properties content is as follows:
Info =\u4f60\u597d\uff01
Message_fr_fr.properties content is as follows:
Info =bonjour\!
message_en_us.properties content is as follows:
Info =hello\!

The content of different resource files will be obtained according to the ISO of locale specified by locale.
Import java.util.ResourceBundle; import Java.util.Locale;p ublic class interdemo02{public static void Main (String args[] {Locale Zhloc = new locale ("zh", "CN"),//indicates Chinese locale enloc = new locale ("en", "us")//indicates US locale frloc = new locale ( "Fr", "fr");//indicates the French region//Find the Chinese property file, you need to specify the locale object of Chinese ResourceBundle ZHRB = resourcebundle.getbundle ("Message", zhloc);// To find the English attribute file, you need to specify the locale object in English resourcebundle ENRB = Resourcebundle.getbundle ("Message", enloc);//Find the French property file, You need to specify a locale object in French resourcebundle FRRB = Resourcebundle.getbundle ("Message", frloc);//Read the contents of each property file sequentially, read by key value, At this point the key value name is unified InfoSystem.out.println ("Chinese:" + zhrb.getstring ("info")); System.out.println ("English:" + enrb.getstring ("info")); System.out.println ("French:" + frrb.getstring ("info"));}};

The above information is indeed read out, but in the development of the program there is a need to pay special attention to the Chinese resource file, although it can be read directly in Chinese, but this is not reasonable, it should be Unicode encoding, converted to Java 16 binary knowledge, this tool for the JDK to provide itself.With the DOS command open Native2ascii.exe and enter the Chinese return, the transcoded characters will be displayed as follows:
remember: As long as it is Chinese, the transcoding operation is required. working with dynamic textall the content in the previous resource file is actually fixed, and if there is some content now, hello,XXX. Then you have to do some dynamic text settings in the resource file, set the placeholder, the contents of these symbols are temporarily indeterminate, but in the execution of the program is set by the program, and to achieve such a function, you must use the Messageform class. This class is defined in the Java.text package. There is also a number formatted format (NUMBERFORMAT), a Date formatted format (DATEFORMAT) in the format class. placeholders are represented as {number} if the first content "{0}", the second content "{1}" is now represented, and so on. The format () method is primarily used in the Messageformat class, and this method is defined as follows:Public static string format (string pattern, Object ... arguments);UseThe text resources are roughly as follows:
The code is as follows:
Import java.util.ResourceBundle; import java.util.Locale; import java.text.*;p ublic class Interdemo03{public static void Main (String args[]) {locale zhloc = new locale ("zh", "CN")//indicates Chinese locale enloc = new locale ("en", "us");//Indicates Loc in the U.S. region Ale frloc = new locale ("fr", "fr");//For the French region//Find the Chinese property file, you need to specify the Locale object for Chinese resourcebundle ZHRB = Resourcebundle.getbundle (" Message ", zhloc);//Find the English attribute file, you need to specify the locale object in English resourcebundle ENRB = Resourcebundle.getbundle (" Message ", enloc);// To find the French attribute file, you need to specify a French locale object ResourceBundle FRRB = Resourcebundle.getbundle ("Message", frloc);//Read the contents of each property file sequentially, read by key value, At this point the key value name is infostring str1 = zhrb.getstring ("info"); String str2 = enrb.getstring ("info"); String STR3 = frrb.getstring ("info"); System.out.println ("Chinese:" + messageformat.format (str1, "刘勋")); System.out.println ("English:" + messageformat.format (str2, "Liuxun")); System.out.println ("French:" + Messageformat.format (STR3, "Liuxun"));}};

You can also set multiple placeholders for working with text.
New Java Features--variable parametersafter JDK1.5, Java added new features to the operation, you can pass the variable parameters to the method, the previously defined method actually has a fixed number of parameters, then after JDK1.5 in order to solve the trouble of operation, added this feature. Test parameter passing:
public class Interdemo04{public static void Main (String args[]) {System.out.print ("First run:"); Fun ("Liuxun", "LiU", "刘勋") ;//pass in three parameters System.out.print ("\ n second run:"), Fun ("Hhxy"),//pass in a parameter}public static void Fun (Object...args) {//fixed syntax, enter any number of data, Use an array representation for (int i=0;i<args.length;i++) {System.out.print (Args[i] + ",");}};

If you feel that the above operation cannot be explicitly expressed, you can also pass an array directly past.
public class Interdemo05{public static void Main (String args[]) {System.out.print ("First run:"); object[] arg1 = {"Liuxun", " LiU "," 刘勋 "}, Fun (ARG1),//pass in three parameters System.out.print (" \ n second run: "); object[] arg2 = {" Hhxy "}; Fun (arg2);// Pass in a parameter System.out.print ("\ n the third run:"); object[] Arg3 = {};//No parameters passed into fun (ARG3);} public static void Fun (Object...args) {//fixed syntax, enter any number of data, using an array representation for (int i=0;i<args.length;i++) {System.out.print ( Args[i] + ",");}};

use a class instead of a resource fileThe above application is already the international practical operation effect. all the content to be displayed should actually be in the resource file, but in Java in order to take care of some of the habits of the users of the class, so you can also directly use a class to hold all the contents of the resource file, but this class in the operation must have a clear point of attention, Must inherit ListResourceBundle. The following information is displayed in Chinese:Resource Class Message_zh_cn.java
Import Java.util.ListResourceBundle;p ublic class Message_zh_cn extends Listresourcebundle{private final Object data[][ ] = {"Info", "Chinese, hello, {0}! "},{" Info2 "," Chinese, graduated from university: {0}! "}};p ublic object[][] getcontents () {//overwrite method return data;};
Note: The resource class inherits the ListResourceBundle class must overwrite the public object[][] getcontents () method to run the Main method:
Import java.util.ResourceBundle; import java.util.Locale; import java.text.*;p ublic class Interdemo06{public static  void Main (String args[]) {locale zhloc = new locale ("zh", "CN");//for Chinese///Find Chinese property file, you need to specify locale object for Chinese resourcebundle ZHRB = Resourcebundle.getbundle ("Message", Zhloc); String str1 = zhrb.getstring ("info"); String str2 = zhrb.getstring ("Info2"); System.out.println ("Chinese:" + messageformat.format (str1, "刘勋")); System.out.println ("Chinese:" + messageformat.format (str2, "Huang Huai College");}};

It is important to note that:The subscript {0}, {1} 、、、 of the placeholder are set in the order of one of the keys. whether it is a resource class or a resource file, when it is found is a message, then if a variety of resource files come out together, then finally find which one? in fact, you need to prioritize at this point:the priority of the resource class is greater than the priority of the resource file, followed by the file name with the region identifier greater than the non-identity. message_zh_cn.class > Message_zh_cn.properties > Message.properties
Summary:The realization idea of internationalization program: The program and the display are separated, according to different locale specified area to find different resource file and obtain corresponding value according to key. of course, in the actual development, including the future to learn struts, are often used in the way of resource files to save all the information content, the basic principle is to rely on the ResourceBundle class to obtain the contents of the resource file. Messageformat is a subclass of format.



Java Common class Libraries-internationalized programs (Locale,resourcebundle and Messageformat processing dynamic text)

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.