Bazaprogram.ru

Новости из мира ПК
5 просмотров
Рейтинг статьи
1 звезда2 звезды3 звезды4 звезды5 звезд
Загрузка...

Java util locale

Java.util.Locale Class

Introduction

The java.util.Locale class object represents a specific geographical, political, or cultural region. .Following are the important points about Locale −

An operation that requires a Locale to perform its task is called locale-sensitive and uses the Locale to form information for the user.

Locale is a mechanism for identifying objects, not a container for the objects themselves.

Class declaration

Following is the declaration for java.util.Locale class −

Field

Following are the fields for java.util.Locale class −

static Locale CANADA − This is the constant for country.

static Locale CANADA FRENCH − This is the constant for country.

static Locale CHINA − This is the constant for country.

static Locale CHINESE − This is the constant for language.

static Locale ENGLISH − This is the constant for language.

static Locale FRANCE − This is the constant for country.

static Locale FRENCH − This is the constant for language.

static Locale GERMAN − This is the constant for language.

static Locale GERMANY − This is the constant for country.

static Locale ITALIAN − This is the constant for language.

static Locale ITALY − This is the constant for country.

static Locale JAPAN − This is the constant for country.

static Locale JAPANESE − This is the constant for language.

static Locale KOREA − This is the constant for country.

static Locale KOREAN − This is the constant for language.

static Locale PRC − This is the constant for country.

static Locale ROOT − This is the constant for root locale.

static Locale SIMPLIFIED CHINESE − This is the constant for language.

static Locale TAIWAN − This is the constant for country.

static Locale TRADITIONAL CHINESE − This is the constant for language.

static Locale UK − This is the constant for country.

static Locale US − This is the constant for country.

>

Sr.No.Constructor & Description1

This constructs a locale from a language code.

Locale(String language, String country)

This constructs a locale from a language code.

Locale(String language, String country, String variant)

This constructs a locale from language, country, variant.

>

Sr.No.Method & Description1Object clone()

This method overrides Cloneable

This method returns true if this Locale is equal to another object.

This method returns an array of all installed locales.

This method returns the country/region code for this locale, which will either be the empty string or an uppercase ISO 3166 2-letter code.

This method gets the current value of the default locale for this instance of the Java Virtual Machine.

This method returns a name for the locale’s country that is appropriate for display to the user.

This method Returns a name for the locale’s country that is appropriate for display to the user.

This method returns a name for the locale’s language that is appropriate for display to the user.

This method returns a name for the locale’s language that is appropriate for display to the user.

This method returns a name for the locale that is appropriate for display to the user.

This method returns a name for the locale that is appropriate for display to the user.

This method returns a name for the locale’s variant code that is appropriate for display to the user.

This method returns a name for the locale’s variant code that is appropriate for display to the user.

This method returns a three-letter abbreviation for this locale’s country.

This method returns returns a three-letter abbreviation for this locale’s language.

This method returns a list of all 2-letter country codes defined in ISO 3166.

This method returns a list of all 2-letter language codes defined in ISO 639.

This method returns the language code for this locale, which will either be the empty string or a lowercase ISO 639 code.

This method returns the variant code for this locale.

This method override hashCode.

This method sets the default locale for this instance of the Java Virtual Machine.

This method is the getter for the programmatic name of the entire locale, with the language, country and variant separated by underbars.

Methods inherited

This class inherits methods from the following classes −

java.util.Locale Example

Posted by: Rohit Joshi in Locale June 3rd, 2014 1 Comment Views

In this article we will discuss about the Locale class from java.util package. The Locale is used to make the system relevant and usable for the users from different cultures. In other words, it is used to customize the system for different people of different region, culture and language.

A Locale object represents a specific geographical, political, or cultural region.

Let’s discuss about the Locale class and how to create, query and use a Locale object.

1. Locale Instantiation

There are many ways to create a Locale object. As of JDK 7, there are four ways to create a Locale object. In the following example, we will see different ways of creating it and differences between them.

1.1 Using constructor

1.1a. Locale(String language) : Construct a locale from a language code. For e.g. “fr” is a language code for French.

1.1.b. Locale(String language, String country) : When you have a language code and a country, you can use this constructor with two parameters that takes a language as first parameter and a country as second parameter to create a locale object.

1.1c. Locale(String language, String country, String variant) : Construct a locale from language, country and variant. Any arbitrary value can be used to indicate a variation of a Locale .

1.2 Using Builder method

From JDK 7 releases, the Locale provides a Builder to create an instance of the Locale class. Using Locale.Builder you can instantiate an object that conforms to BCP 47 syntax.

Locale localeFromBuilder = new Locale.Builder().setLanguage(«en»).setRegion(«GB»).build();

1.3 Using forLanguageTag method:

forLanguageTag (String languageTag) returns a locale for the specified IETF BCP 47 language tag string. If the specified language tag contains any ill-formed subtags, the first such subtag and all the following subtags are ignored.

Locale forLangLocale = Locale.forLanguageTag(«en-GB»);

1.4 Locale constants

Java provides a set of pre-defined constants for some languages and countries. If a language constant is specified, then the regional portion of that locale is undefined.

Locale localeCosnt = Locale.FRANCE;

  • If we run the above code, we will have the following results:

Although, you can use any of these ways to create a locale object. But it is recommended to use forLanguageTag and Locale.Builder methods. The reason is these two methods return a locale for the specified IETF BCP 47 language tag string. BCP 47 imposes syntax restrictions that are not imposed by Locale’s constructors. This means that conversions between some Locales and BCP 47 language tags cannot be made without losing information.

2. Methods

In this section, we will discuss about some of the important methods of the Locale class. You can use these methods on a locale object to get some information about the Locale .

  • If we run the above code, we will have the following results:

Please note that in the above example, we have printed only that script and variant which are specified for the locale object.

Locale.getDefault() gets the current value of the default locale for current instance of the Java Virtual Machine. The Java Virtual Machine sets the default locale during startup based on the host environment.

Locale.getAvailableLocales() returns an array of all available locales installed on that particular JVM machine.

String getDisplayName() is an instance method which returns the name of the locale object (appropriate to display) in string form. The name contains values returned by getDisplayLanguage(), getDisplayScript(),getDisplayCountry(), and getDisplayVariant() methods .

String getLanguage() returns the language code of the locale object.

String getDisplayLanguage() returns the name of the locale’s language. It shows an appropriate name for display to the user.

String getCountry() returns the country/region code for this locale, which should either be the empty string, an uppercase ISO 3166 2-letter code, or a UN M.49 3-digit code.

String getDisplayCountry() returns the name of the locale’s country. It shows an appropriate name for display to the user.

String getScript() returns the script code for this locale. It should either be the empty string or an ISO 15924 4-letter script code. The first letter is uppercase and the rest are lowercase, for example, ‘Latn’, ‘Cyrl’.

String getDisplayScript() returns the name of the locale’s script appropriate for display to the user.

String getVariant() returns the variant code, or the empty string if none is defined.

String getDisplayVariant() returns a name for the locale’s variant code that is appropriate for display to the user.

3. Locale sensitive classes

The Locale is the mechanism for identifying the kind of object that you would like to get. Java provides certain classes which provide locale specific operations. For example, they provide methods to format values that represent dates, currency and numbers according to a specific locale. These classes are known as Locale sensitive classes.

In the following example, we will use NumberFormat , Currency , and DateFormat classes to illustrate about locale sensitive operations.

  • If we run the above code, we will have the following results:

In the above example, we have used the getInstance() static method to get the instance about the respective class. The getInstance() methods used in two variety one without locale (which uses the default locale set in the current instance of the JVM) and another with a Locale as its parameter.

You can clearly see the differences in the output due to difference in the locale object used.

This was an example of how to use the Locale class and some of its basic methods.

Java util locale

Кто о чем, а я опять о джаве. На этот раз речь пойдет о локализации. Под локализацией подразумевается отображение данных (прежде всего пользовательского интерфейса) на языке пользователя. Наиболее ярким примером различия представления данных, по-моему, является отображение даты — в России принят формат День, Месяц, Год, а в США — Месяц, День, Год. Грамотно написанная программа должна эти различия учитывать.

Основным классом, отвечающим за разное представление данных в разных странах, является в java класс java.util.Locale . Существует целый набор стандартных локалей, идентифицируются они в основном по двум параметрам — языку и стране, иногда может добавляться платформа — Windows или Unix. Все доступные локали можно посмотреть следующей программкой.

Список будет выглядеть примерно так: en_US, en_UK, en, ru_RU и т.д. Первая часть каждого слова — язык, вторая часть — страна. Иногда встречаются конструкции вида ru_RU_UNIX . Т.е. локаль для русских юникс-машин, расположенных в России. На каждом компьютере своя локаль по умолчанию, у меня, да и большинства российских пользователей, полагаю — ru_RU . Узнать собственную локаль можно следующей командой: System.out.println(Locale.getDefault());

А вот теперь самое интересное. Допустим, мы хотим написать программу, которая приветствует пользователя на его языке. Как это сделать? Наиболее очевидный и неправильный способ — воспользоваться условными конструкциями типа if или switch . Работать будет, но при необходимости добавить не предусмотренный заранее язык придется править программу, а это неправильно. Более правильный способ — вынести все требующие перевода фразы в текстовый файл. Тогда добавление нового языка не потребует редактирования программы. Для этих целей в java существует класс java.util.ResourceBundle . Он работает с парами ключ-значение, которые хранятся в специальных файлах ресурсов — текстовых файлах с расширением .properties . Вот как можно его использовать в нашей программе-приветствии:

Если запустить программу в приведенном виде, получим исключение MissingResourceException . О том, как исправить положение — ниже, пока же о том, что должен делать код.

Класс ResourceBundle абстрактный, поэтому получить его экземпляр можно исключительно с помощью статического метода getBundle . Последний имеет несколько перегруженных реализаций, в данном случае использован вариант, который принимает на вход только имя файла ресурсов.

Конструкция res.getString(«greetings») получает из файла ресурсов значение пары ключ-значение по известному ключу, в данном случае — greetings . Отсюда вывод — в различный файлах ресурсов ключ должен быть одинаковым.

Теперь, чтобы программа заработала, создадим файл ресурсов. В любом текстовом редакторе создайте новый файл и запишите туда следующее:

Сохраните файл под именем data.properties в папку с программой и запустите программу снова. Теперь программа отработает без исключений и выдаст на экран «Hello!». Создадим теперь текстовый файл data_ru.properties с содержанием

Если ваша локаль по умолчанию отличается от ru_RU , то и файл вам надо назвать по другому: data_ .pro perties. Т.е. в случае локали en_UK файл надо назвать data_en.properties, в случае fr_CA — data_fr.properties и т.д. Запустите программу снова. Будет выдано «Hello, World!», не так ли?

Дело в том, что java будет искать файл ресурсов от более частного к более общему. Если ресурс называется data, а локаль — ru_RU_UNIX , то поиск файла ресурсов будет вестись в следующем порядке:

Поэтому, чтобы избежать исключения MissingResourceException , подобные локализованные программы всегда надо снабжать файлом ресурсов по умолчанию, т.е. без указания языка и страны. В нашем случае это файл data.properties. Также понятно, что для локализации достаточно снабдить пользователя соответствующим файлом ресурсов, выбран же он будет автоматически. В случае больших программ целесообразно иметь несколько файлов с ресурсами. В одном хранить, скажем, данные пользовательского интерфейса, в другом — локализованные сообщения об ошибках и т.д.

При использовании этого способа локализации могут возникнуть проблемы с не-английским языком. Создайте файл data_ru_RU.properties, и запишите туда

При запуске программы место ожидаемого «Привет!» получим что-то вроде «. «, т.е. нечто абсолютно нечитаемое. Получается эта ерунда из-за проблем с кодировкой, а решается применением стандартной утилиты native2ascii. Переименуйте ваш файл data_ru_RU.properties например, в data.txt и запустите команду

native2ascii data.txt data_ru_RU.properties

На выходе получите файл ресурсов, в которых все не-латинские буквы будут заменены их шестнадцатеричными кодами. И вот теперь при запуске программы получим правильный результат — «Привет!».

Java Locale > July 13, 2014 by Krishna Srinivasan Leave a Comment

A locale is a set of parameters which represents specific locale such as geographic region or political region that shares the same language and customs. A locale object may includes user’s language, country, and any special variant preferences that user needs. A Locale class which requires operation to perform its task is called as locale-sensitive and uses Locale to provide information for the user.

Locale object is a just an identifier for region, where Locale validity checking is not performed. For example, if we want to display the number which is referred as locale-sensitive operation where the number format should be formatted according to the customs and conventions of the user’s native country, region, or culture. A Locale is not a container for the objects, it is a just mechanism for identifying an objects.

Locale Class Declaration

Locale Class Constructors

  • Locale(String language(): This constructor creates new Locale from the specified language.
  • Locale(String language, String country): This constructor specifies a Locale object with language and country code.
  • Locale(String language, String country, String variant): This constructor creates a Locale object with language, country code and variant.

Locale Class Example

Below example demonstrate use of Locale class.

  • In the above example, we have used different methods i.e. getAvailableLocales(), getDisplayName() and getDisplayCountry( ) methods.
  • The getAvailableLocales() method is used to get an array of object.
  • The getDisplayName() method displays the name for current locale that user wants to display.
  • The getDisplayCountry( ) method specifies the name for the locale’s country.

When you run the above example, you would get the following output:

Locale >

FieldsDescriptionstatic Locale CANADAThis field is constant for country en_CA.static Locale CANADA_FRENCHThis field is constant for country fr_CA.static Locale CHINAThis field is constant for country zh_CN.static Locale CHINESEThis field is constant for language zh.static Locale ENGLISHThis field is constant for language en.static Locale FRANCEThis field is constant for country fr_FR.static Locale FRENCHThis field is constant for language fr.static Locale GERMANThis field is constant for language de.static Locale GERMANYThis field is constant for country de_DE.static Locale ITALIANThis field is constant for language it_CH.static Locale ITALYThis field is constant for country it_IT.static Locale JAPANThis field is constant for country ja_JP.static Locale JAPANESEThis field is constant for language ja.static Locale KOREAThis field is constant for country ko_KR.static Locale KOREANThis field is constant for language ko.static Locale PRCThis field is constant for country zh_CN.static Locale ROOTThis field is constant for the root locale .static Locale SIMPLIFIED CHINESEThis field is constant for language zh_CN .static Locale TAIWANThis field is constant for country zh_TW .static Locale TRADITIONAL_CHINESEThis field is constant for language zh_TW .static Locale UKThis field is constant for country en_GB .static Locale USThis field is constant for country en_US .

Locale >

MethodsDescriptionObject clone()This method returns copy of the cloneable object.boolean equals(Object obj)It compares this locale with another object and returns true if they are eqaul.Locale [ ] getAvailableLocales()This method returns the list of all system’s installed locales.String getCountry()It returns the country code for this locale.Static Locale getDefault()This method returns the user’s preferred locale.String getDisplayCountry()This method returns the name of the locale’s country, localized to locale.String getDisplayLanguage()This method returns a name for the locale’s language that the user wants to display.String getDisplayLanguage(Locale)This method returns a name for the locale’s language that user wants to display.String getDisplayName()This method returns a name for the locale that the user want to display.String getDisplayName(Locale)This method returns a name for the locale that the user want to display.String getDisplayVariant()This method returns variant name for the variant code in the default Locale.String getDisplayVariant(Locale)This method returns variant name for the variant code in the default LocaleString getISO3Country()It returns three-letter ISO 3166 country code for this locale’s country.String getISO3Language()This method returns a three-letters ISO 639-2/T language code which is corresponds to the language code for this locale.static String[ ] getISOCountries()This method returns an array of all two-letter country code defined in ISO 3166.static String[ ] getISOLanguages()This method returns an array of all two-letter language codes defined in ISO 639.String getLanguage()This method returns the Locale language code which will be either empty string or lowercase.String getVariant()This method returns the locale variant code.int hashCode()This returns an integer hash code for this locale.void setdefault(Locale)This method is used to set default locale for this instance of the JVM(Java Virtual Machine).String toString()This method returns the string representation of this Locale which includes language country and variant.

Locale Class Methods Example

  • In the above example, we have used different methods such as getAvailableLocales(), getDisplayName(),getCountry( ), getVariant( ), getLanguage() methods.
  • The getAvailableLocales() method is used to get an array of object.
  • The getDisplayName() method displays the name for current locale that user wants to display.
  • The getCountry( ) method specifies the country code for this locale.
  • The getVariant( ) method specifies the variant code for this Locale.
  • The getLanguage() method is used to get the language code for this Locale.

When you run the above example, you would get the following output:

Читать еще:  Java lang arraystoreexception
Ссылка на основную публикацию
Adblock
detector