June 2001
Intermediate to advanced
888 pages
21h 1m
English
You want to
change the default
Locale for all operations within a given Java
runtime.
Set the
system property
user.language, or call Locale.setDefault( )
.
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));
}
}