Java Learning Note 12--internationalization

Source: Internet
Author: User
Tags diff string format

Internationalized operation means that a program can adapt to multiple languages at the same time, that is, if the program is Chinese, it will display the text in Chinese, if now

The user of the program is English, it will be displayed in the text, that is, can be internationalized operation, so that a program to adapt to the language requirements of each country.

The program finds different resource files according to different language environment, then extracts the contents from the resource files, and the contents of the resource files are saved in the form of Key->value.

Therefore, when reading, the corresponding value is found by its key.

Support classes for internationalization implementations

If you want to implement the internationalization of a Java program, you must complete the following three classes:

Java.util.Locale: Used to represent a national language class.

Java.util.ResourceBundle: Used to access resource files.

Java.text.MessageFormat: A placeholder string that formats the resource file.

Local class

Local is represented locally and is actually using an ISO-encoded encapsulation class. There is a unique code for each country,

Then this code is called the ISO code, and using local can specify a specific country code. For example:

    • China's code: ZH_CH

    • English-American code: en-US

    • Code for French: FR-FR

ResourceBundle

This class is specialized to complete the property file read operation, read the time directly specify the name of the file (this filename does not normally need to specify a suffix,

Suffix unified to *.properties), you can automatically select the required resource files based on the locale code specified by locale.

public static final ResourceBundle Getbundle (String baseName) This method specifies the resource file to manipulate, and this method finds the default operating system's language locale object
public static final ResourceBundle getbundle (String basename,locale Locale) This method is also the resource file for the specified operation and passes in the locale object
Public final string getString (string key) The corresponding value is obtained according to Key

The following is a program to observe the use of resource files, and how to use ResourceBundle to read resource files.

Message.properties
info=HELLO  
PackageCom.Itmyhome;ImportJava.util.ResourceBundle;PublicClassT{public static void main (string[] args)  Throws exception{resourcebundle rb = resourcebundle. Getbundle ( "message" system.. (rb. Getstring ( "info" } }             /span>                

PS:message.properties The default lookup path is classpath, if it is not under this path and the full package pathname is specified, the following exception will be reported

Can‘t find bundle for base name message, locale zh_CH

Java Internationalization Program implementation

You can export different countries according to different countries Hello:

English: Hello!

English: Hello

French: bonjour!

Define the different resource files separately, at this time need to define three resource files, while defining the resource file, you need to specify the language encoding for this resource file:

English: Message_zh_ch.properties

English: Message_en_us.properties

French: Message_fr_fr.properties

Message_zh_cn.properties
info=\u4f60\u597d
Message_en_us.properties
info=Hello
Message_fr_fr.properties
info=Bonjour
PackageCom.Itmyhome;ImportJava.util.Locale;ImportJava.util.ResourceBundle;PublicClassT{PublicStaticvoidMain(String[]Args)ThrowsException{LocaleZhlocale=NewLocale("EN","CN");Represents the Chinese regionLocaleEnlocale=NewLocale("EN","US");Represents the United States regionLocaleFrlocale=NewLocale("FR","FR");Representing the French regionResourceBundleZhrb=ResourceBundle.Getbundle("Message",Zhlocale);ResourceBundleEnrb=ResourceBundle.Getbundle("Message",Enlocale);ResourceBundleFrrb=ResourceBundle.Getbundle("Message",Frlocale);Systemout. (zhrb. Getstring ( "info" system.. (enrb. Getstring ( "info" system.. (frrb. Getstring ( "info" } }             /span>                

PS: If the above Chinese attribute is in Chinese, it should be Unicode encoded, so as to avoid some of the problems caused by the system garbled

Working with dynamic text

All the content in the previous resource file is actually fixed, and if there is some content now, Hello, XXX. At this point, you have to do something in the resource file

Dynamic text configuration, set placeholders, the contents of these symbols are temporarily not fixed, but when the program is executed by the program to set up,

To implement such a feature, you must use the Messageformat class. This class is defined in the Java.text package.

Placeholders are expressed in the form of (numbers), if the first content "{0}" and the second content "{1}" are now represented in turn.

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)

info=\u4f60\u597d{0}  info=Hello,{0}  info=Bonjour,{0}
PackageCom.Itmyhome;ImportJava.text.MessageFormat;ImportJava.util.Locale;ImportJava.util.ResourceBundle;PublicClassT{PublicStaticvoidMain(String[]Args)ThrowsException{LocaleZhlocale=NewLocale("EN","CN");Represents the Chinese regionLocaleEnlocale=NewLocale("EN","US");Represents the United States regionLocaleFrlocale=NewLocale("FR","FR");Representing the French regionResourceBundleZhrb=ResourceBundle.Getbundle("Message",Zhlocale);ResourceBundleEnrb=ResourceBundle.Getbundle("Message",Enlocale);ResourceBundleFrrb=ResourceBundle.Getbundle("Message",Frlocale);System.Out.println(Messageformat.Format(Zhrb.GetString("Info"),"Itmyhome"));System.out. (messageformat. Format (enrb. Getstring ( "info"  "Itmyhome" ) ; system.. (messageformat. Format (frrb. Getstring ( "info"  "Itmyhome" ) ; } }             /span>                

New Java features, variable parameters

After JDK1.5, Java added new features to the operation, you can pass a variable parameter to the method, the previously defined method, in fact, the parameters are fixed number of

PackageCom.Itmyhome;PublicClassT{PublicStaticvoidMain(String[]Args)ThrowsException{Fun("Java","C + +",". Net");Fun("Itmyhome");}PublicStaticvoid fun (objectargs) {for  (int i = 0i < args. Lengthi++) {system. Err. (args[i]+ } } }          /span>                
Use a class instead of a resource file

You can also use a class directly to hold all of the resource file contents, but this class must have an obvious point of note when operating, and must inherit ListResourceBundle

Message_zh_cn

PackageCom.Itmyhome;ImportJava.util.ListResourceBundlepublic class MESSAGE_ZH_CN extends listresourcebundle {private final object date[][] = { { "info" , "hello" } } ;  @Override protected object[][] getcontents () {//TODO auto-generated Method stub return date} }             /span>                

Read Resource class

PackageCom.Itmyhome;ImportJava.util.Locale;ImportJava.util.ResourceBundle;PublicClassT{PublicStaticvoidMain(String[]Args)ThrowsException{LocaleZhlocale= new locale ( "en" , "CN" ); //represents China region resourcebundle zhrb =  Resourcebundle. ( "com.itmyhome.Message" ,zhlocale //write full pathname system.. (zhrb. Getstring ( "info" } }             /span>                

Whether it is a resource class or a resource file, when the search is a message, then if a variety of resource files come out together, then the final look for which one?

In fact, you need to prioritize at this point:

Message_zh_cn.class

Message_zh_cn.properties

Message.properties

Summary: The idea of internationalization program realization: The program is separated from the display, and the different resource files are found according to the locale specified by different locale and the corresponding value is obtained according to their key.

Copyright NOTICE: This article uses the BY-NC-SA agreement to authorize, reproduced the Wheat Field Technical blog article please indicate the source

Original address: Http://itmyhome.com/2015/03/java-study-notes-internationalization

Java Learning Note 12--internationalization

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.