Recipe 15.9 Setting the Default Locale


Problem

You want to change the default Locale for all operations within a given Java runtime.

Solution

Set the system property user.language or call Locale.setDefault( ) .

Discussion

Here is a program called SetLocale, which takes the language and country codes from the command line, constructs a Locale object, and passes it to Locale.setDefault( ). When run with different arguments, it prints the date and a number in the appropriate locale:

C:\javasrc\i18n>java SetLocale en US 6/30/00 1:45 AM 123.457 C:\javasrc\i18n>java SetLocale fr FR 30/06/00 01:45 123,457

The code is similar to the previous recipe in how it constructs the locale:

import java.text.*; import java.util.*; /** Change the default locale */ public class SetLocale {     public static void main(String[] args) {         switch (args.length) {         case 0:             Locale.setDefault(Locale.FRANCE);             break;         case 1:             throw new IllegalArgumentException( );         case 2:             Locale.setDefault(new Locale(args[0], args[1]));             break;         default:             System.out.println("Usage: SetLocale [language [country]]");             // FALLTHROUGH         }         DateFormat df = DateFormat.getInstance( );         NumberFormat nf = NumberFormat.getInstance( );         System.out.println(df.format(new Date( )));         System.out.println(nf.format(123.4567));     } }



Java Cookbook
Java Cookbook, Second Edition
ISBN: 0596007019
EAN: 2147483647
Year: 2003
Pages: 409
Authors: Ian F Darwin

Similar book on Amazon

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net