Internationalization in Java

Source: Internet
Author: User
Tags dateformat i18n numeric locale numeric value


Internationalization, English is called internationalization word too long, and is referred to as i18n (take the head to take the middle of the tail 18 letters) without shouting, this is OK! Then look at internationalization, which means that the product or program can adapt to the needs of different languages and regions without having to make any changes. Also greet in China you will say "Hello", in the United States you will say "Hello", you see, you are already i18n.



Internationalization in Java is primarily a tool class resourcebundle, the core idea is to provide a different resource file for different locales. So let's take a look at how the resource file is defined.



Define the corresponding resource file, we put the resource file in a resource bundle (which is the usual package), each resource file in a resource bundle must have a common base name. In addition to the base name, the name of each file must also have an additional part that identifies its local information, for example: the base name of a resource bundle is "message", the resource filenames corresponding to the Chinese (Chinese), English (United States) environment are:
Message_zh_cn.properties
Message_en_us.properties






It is important to note that the resource file is usually in the form of a key-value pair, and the resource file is in the properties format file, so all the characters in the file must be ASCLL code, cannot be saved in Chinese, Java provides the NATIVE2ASCLL tool to convert Chinese is the ASCLL code. So when writing the properties file is written in Chinese, a return to the car is automatically encoded.






Here is the specific code, in the Java API provides a resourcebundle class to describe a resource bundle, and the ResourceBundle class provides a corresponding static method Getbundle, which can be automatically bound according to the country region of the visitors corresponding The resource file.


Import java.util.Locale;
Import java.util.ResourceBundle;

Public class I18n{

     Public static void test() {
         / / Set a custom language country code
         Locale locale1 = new Locale("en_US");
         Locale locale2 = Locale.getDefault();
         / / Get the resource file
         ResourceBundle rb = ResourceBundle.getBundle("message.i18n.message", locale2);
         / / Get the corresponding key value
         String greeting = rb.getString("greeting");
         String userInfo = rb.getString("name");

         System.out.println(greeting);
         System.out.println(userInfo);
     }

     Public static void main(String[] args) {
         Test();
     }
}
//Hello there
//yu 6 road 


The above is the internationalization of some fixed text, fixed text including the menu name, navigation bar, system information, etc., are manually configured in the properties file, but some data, for example, value, currency, time, date, etc. because it may be generated dynamically during the operation of the program, it can not be as simple as text To separate them from the application and require special handling. Java provides an API to address these issues.



Let's just say the Locale class, the English introduction is like this


A Locale object represents a specific geographical, political, or cultural region. An operation, requires a locale to perform it task is called Locale-sensitive and uses the locale to tailor Informati On for the user.


The Locate object represents a particular geographical, political, or cultural area. Operations that require Locate settings to perform tasks are called sensitive areas (classes that contain Locate are sensitive areas) and use Locate to customize information for users.



On the internationalization of the date we use the tool class DateFormat and look at the structure diagram of the class.






DateFormat has a lot of different constructors, and in the constructor can also specify a different time display mode, I do not show each one, the following shows an example code.


Public class DateFormatTest {

    Public static void main(String[] args) throws ParseException {

        Date date = new Date();

        DateFormat df = DateFormat.getDateInstance(DateFormat.DEFAULT, Locale.CHINA);
        String str = df.format(date);
        System.out.println(str); // 2018-8-6

        Df = DateFormat.getTimeInstance(DateFormat.LONG, Locale.CHINA);
        System.out.println(df.format(date)); // 07:58:26 PM

        Df = DateFormat.getDateTimeInstance(DateFormat.FULL, DateFormat.SHORT, Locale.CHINA);
        System.out.println(df.format(date)); // Monday, August 6, 2018 7:58 PM

        / / Get the default DateFormat
        Df = DateFormat.getInstance();
        System.out.println(df.format(date)); // 18-8-6 7:58 PM

        // Use DateFormat to reverse format a string into a date object
        String dateString = "Monday, August 6, 2018, 7:58 PM";
        DateFormat df2 = DateFormat.getDateTimeInstance(DateFormat.FULL, DateFormat.SHORT, Locale.CHINA);
        Date date2 = df2.parse(dateString); // There may be an exception here, and the format of the string will be incorrect if it is inconsistent with the format set by DateFormat.
        System.out.println(date2); // Mon Aug 06 19:58:00 CST 2018
    }
} 


Dynamic text internationalization using the tool class Messageformat, Messageformat allows developers to replace sensitive data in strings (that is, internationalized related data) in strings with {0} {1} {2} {3} as placeholders.


Public class MessageFormatTest {
     Public static void main(String[] args) {
         /*  Test Data
             Greeting=Welcome
             Name=YJK
             Age=18
             Pattern={0},{1},your age is {2}.
          */
         ResourceBundle rb = ResourceBundle.getBundle("message.i18n.message_en_US",Locale.US);
         String greeting = rb.getString("greeting");
         String name = rb.getString("name");
         String age = rb.getString("age");

         / / Get the pattern string
         String pattern = rb.getString("message");

         // instantiate the MessageFormat object and load the corresponding pattern string
         MessageFormat format = new MessageFormat(pattern);
         // The format method requires an array of Objects.
         Object[] params = {greeting, name, age};
         // format the pattern string, the corresponding replacement object for the specified placeholder in the parameter array
         String string = format.format(params);
         System.out.println(string);
     }
}
//Welcome, YJK, your age is 18. 


The NumberFormat class can format a numeric value string that conforms to a country's local customs, or it can parse a numeric string that conforms to a country's locale to a corresponding numeric value. The corresponding methods are format and parse respectively.


Public class NumberFormatTest {
    Public static void main(String[] args) throws ParseException{

        Int price = 18;
        // NumberFormat nf = NumberFormat.getCurrencyInstance(Locale.CHINA); // ¥18.00
        // NumberFormat nf = NumberFormat.getCurrencyInstance(Locale.US); // $18.00
        // NumberFormat nf = NumberFormat.getCurrencyInstance(Locale.JAPAN); // ¥18
        // Get the NumberFormat instance object that handles the currency
        NumberFormat nf = NumberFormat.getCurrencyInstance(Locale.FRANCE); // 18,00 €
        System.out.println(nf.format(price));

        String s = "18,00 €";
        Nf = NumberFormat.getCurrencyInstance(Locale.FRANCE);

        // parsed in French currency 18,00 € The result is 18.0
        System.out.println(nf.parse(s).doubleValue());

        Double d = 0.1;
        // Get the NumberFormat instance object that handles the integer.
        Nf = NumberFormat.getIntegerInstance(); // 0

        // Get the NumberFormat instance object that handles the percentage value
        Nf = NumberFormat.getPercentInstance();

        System.out.println(nf.format(d)); // 10%

    }
} 




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.