resourcebundle java что это

Resourcebundle java что это

Each resource bundle in a family contains the same items, but the items have been translated for the locale represented by that resource bundle. For example, both «MyResources» and «MyResources_de» may have a String that’s used on a button for canceling operations. In «MyResources» the String may contain «Cancel» and in «MyResources_de» it may contain «Abbrechen».

If there are different resources for different countries, you can make specializations: for example, «MyResources_de_CH» contains objects for the German language (de) in Switzerland (CH). If you want to only modify some of the resources in the specialization, you can do so.

When your program needs a locale-specific object, it loads the ResourceBundle class using the getBundle method:

Resource bundles contain key/value pairs. The keys uniquely identify a locale-specific object in the bundle. Here’s an example of a ListResourceBundle that contains two key/value pairs:

You retrieve an object from resource bundle using the appropriate getter method. Because «OkKey» and «CancelKey» are both strings, you would use getString to retrieve them:

ResourceBundle.Control

Cache Management

Example

Nested Class Summary

Nested Classes

Modifier and TypeClass and Description
static classResourceBundle.Control

Field Summary

Fields

Modifier and TypeField and Description
protected ResourceBundleparent

Constructor Summary

Method Summary

Methods

Modifier and TypeMethod and Description
static voidclearCache()

Methods inherited from class java.lang.Object

Field Detail

parent

Constructor Detail

ResourceBundle

Method Detail

getString

getStringArray

getObject

getLocale

setParent

getBundle

getBundle

getBundle

getBundle

getBundle

getBundle uses the base name, the specified locale, and the default locale (obtained from Locale.getDefault ) to generate a sequence of candidate bundle names. If the specified locale’s language, script, country, and variant are all empty strings, then the base name is the only candidate bundle name. Otherwise, a list of candidate locales is generated from the attribute values of the specified locale (language, script, country and variant) and appended to the base name. Typically, this will look like the following:

Candidate bundle names where the final component is an empty string are omitted, along with the underscore. For example, if country is an empty string, the second and the fifth candidate bundle names above would be omitted. Also, if script is an empty string, the candidate names including script are omitted. For example, a locale with language «de» and variant «JAVA» will produce candidate names with base name «MyResource» below. In the case that the variant contains one or more underscores (‘_’), a sequence of bundle names generated by truncating the last underscore and the part following it is inserted after a candidate bundle name with the original variant. For example, for a locale with language «en», script «Latn, country «US» and variant «WINDOWS_VISTA», and bundle base name «MyResource», the list of candidate bundle names below is generated:

Note: For some Locale s, the list of candidate bundle names contains extra names, or the order of bundle names is slightly modified. See the description of the default implementation of getCandidateLocales for details.

This continues until a result resource bundle is instantiated or the list of candidate bundle names is exhausted. If no matching resource bundle is found, the default control’s getFallbackLocale method is called, which returns the current default locale. A new sequence of candidate locale names is generated using this locale and and searched again, as above.

If still no result bundle is found, the base name alone is looked up. If this still fails, a MissingResourceException is thrown.

Otherwise, getBundle examines the remainder of the candidate locale list that was used during the pass that generated the result resource bundle. (As before, candidate bundle names where the final component is an empty string are omitted.) When it comes to the end of the candidate list, it tries the plain bundle name. With each of the candidate bundle names it attempts to instantiate a resource bundle (first looking for a class and then a properties file, as described above).

Whenever it succeeds, it calls the previously instantiated resource bundle’s setParent method with the new resource bundle. This continues until the list of names is exhausted or the current bundle already has a non-null parent.

Once the parent chain is complete, the bundle is returned.

Note: getBundle caches instantiated resource bundles and might return the same resource bundle instance multiple times.

Note:The baseName argument should be a fully qualified class name. However, for compatibility with earlier versions, Sun’s Java SE Runtime Environments do not verify this, and so it is possible to access PropertyResourceBundle s by specifying a path name (using «/») instead of a fully qualified class name (using «.»).

Источник

Resourcebundle java что это

Each resource bundle in a family contains the same items, but the items have been translated for the locale represented by that resource bundle. For example, both «MyResources» and «MyResources_de» may have a String that’s used on a button for canceling operations. In «MyResources» the String may contain «Cancel» and in «MyResources_de» it may contain «Abbrechen».

If there are different resources for different countries, you can make specializations: for example, «MyResources_de_CH» contains objects for the German language (de) in Switzerland (CH). If you want to only modify some of the resources in the specialization, you can do so.

When your program needs a locale-specific object, it loads the ResourceBundle class using the getBundle method:

Resource bundles contain key/value pairs. The keys uniquely identify a locale-specific object in the bundle. Here’s an example of a ListResourceBundle that contains two key/value pairs:

You retrieve an object from resource bundle using the appropriate getter method. Because «OkKey» and «CancelKey» are both strings, you would use getString to retrieve them:

The implementation of a ResourceBundle subclass must be thread-safe if it’s simultaneously used by multiple threads. The default implementations of the non-abstract methods in this class, and the methods in the direct known concrete subclasses ListResourceBundle and PropertyResourceBundle are thread-safe.

ResourceBundle.Control

Cache Management

Example

Nested Class Summary

Nested Classes

Modifier and TypeClass and Description
static classResourceBundle.Control

Field Summary

Constructor Summary

Method Summary

All Methods Static Methods Instance Methods Abstract Methods Concrete Methods

Modifier and TypeMethod and Description
static voidclearCache ()

Methods inherited from class java.lang.Object

Field Detail

parent

Constructor Detail

ResourceBundle

Method Detail

getBaseBundleName

getString

getStringArray

getObject

getLocale

setParent

getBundle

getBundle

getBundle

getBundle

getBundle

This method behaves the same as calling getBundle(String, Locale, ClassLoader, Control) passing a default instance of ResourceBundle.Control unless another ResourceBundle.Control is provided with the ResourceBundleControlProvider SPI. Refer to the description of modifying the default behavior.

getBundle uses the base name, the specified locale, and the default locale (obtained from Locale.getDefault ) to generate a sequence of candidate bundle names. If the specified locale’s language, script, country, and variant are all empty strings, then the base name is the only candidate bundle name. Otherwise, a list of candidate locales is generated from the attribute values of the specified locale (language, script, country and variant) and appended to the base name. Typically, this will look like the following:

Candidate bundle names where the final component is an empty string are omitted, along with the underscore. For example, if country is an empty string, the second and the fifth candidate bundle names above would be omitted. Also, if script is an empty string, the candidate names including script are omitted. For example, a locale with language «de» and variant «JAVA» will produce candidate names with base name «MyResource» below. In the case that the variant contains one or more underscores (‘_’), a sequence of bundle names generated by truncating the last underscore and the part following it is inserted after a candidate bundle name with the original variant. For example, for a locale with language «en», script «Latn, country «US» and variant «WINDOWS_VISTA», and bundle base name «MyResource», the list of candidate bundle names below is generated:

Note: For some Locale s, the list of candidate bundle names contains extra names, or the order of bundle names is slightly modified. See the description of the default implementation of getCandidateLocales for details.

This continues until a result resource bundle is instantiated or the list of candidate bundle names is exhausted. If no matching resource bundle is found, the default control’s getFallbackLocale method is called, which returns the current default locale. A new sequence of candidate locale names is generated using this locale and and searched again, as above.

If still no result bundle is found, the base name alone is looked up. If this still fails, a MissingResourceException is thrown.

Once a result resource bundle has been found, its parent chain is instantiated. If the result bundle already has a parent (perhaps because it was returned from a cache) the chain is complete.

Otherwise, getBundle examines the remainder of the candidate locale list that was used during the pass that generated the result resource bundle. (As before, candidate bundle names where the final component is an empty string are omitted.) When it comes to the end of the candidate list, it tries the plain bundle name. With each of the candidate bundle names it attempts to instantiate a resource bundle (first looking for a class and then a properties file, as described above).

Whenever it succeeds, it calls the previously instantiated resource bundle’s setParent method with the new resource bundle. This continues until the list of names is exhausted or the current bundle already has a non-null parent.

Once the parent chain is complete, the bundle is returned.

Note: getBundle caches instantiated resource bundles and might return the same resource bundle instance multiple times.

Note:The baseName argument should be a fully qualified class name. However, for compatibility with earlier versions, Sun’s Java SE Runtime Environments do not verify this, and so it is possible to access PropertyResourceBundle s by specifying a path name (using «/») instead of a fully qualified class name (using «.»).

Источник

Руководство по ResourceBundle

1. Обзор

Многие разработчики программного обеспечения в ходе своей профессиональной карьеры сталкиваются с возможностью разрабатывать многоязычные системы или приложения. Обычно они предназначены для конечных пользователей из разных регионов или разных языковых областей.

Эти приложения всегда сложно поддерживать и расширять. Как правило, очень важно иметь возможность одновременно работать с различными данными, относящимися к локализации. Модификация данных приложения должна быть максимально простой без перекомпиляции. Вот почему мы обычно избегаем жесткого кодирования названий ярлыков или кнопок.

К счастью, мы можем рассчитывать на Java, которая предоставляет нам этот класс, который помогает нам решать все проблемы, упомянутые выше.

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

1.1. ResourceBundles

Важно, чтобы мы могли добавить код страны, если код языка уже есть, или платформу, если есть коды языка и страны.

Давайте посмотрим на примеры имен файлов:

Файлы свойств представлены PropertyResourceBundle. Они хранят данные в виде пар ключ-значение с учетом регистра.

Давайте проанализируем образец файла свойств:

Как мы видим, существует три разных стиля определения пар ключ-значение.

Для каждой локали нам нужно создать отдельный класс Java.

Вот образец класса:

Файлы Java имеют одно главное преимущество перед файлами свойств, которое заключается в возможности содержать любой объект, который мы хотим, а не только строки.

С другой стороны, каждая модификация или введение нового java-класса, зависящего от локали, требует перекомпиляции приложения, тогда как файлы свойств могут быть расширены без каких-либо дополнительных усилий.

2. Используйте пакеты ресурсов

Мы уже знаем, как определять пакеты ресурсов, поэтому готовы его использовать.

Рассмотрим фрагмент короткого кода:

Также существует фабричный метод, который требует только имя пакета, если языковой стандарт по умолчанию подходит. Как только у нас есть объект, мы можем получать значения по их ключам.

3. Выбор подходящего ресурса пакета

Если мы хотим использовать ресурс пакета, важно знать, как Java выбирает файлы пакета.

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

Затем перейдем к более общим. Если совпадений нет, он возвращается к языку по умолчанию без проверки платформы на этот раз.

В случае несовпадения он попытается прочитать пакет по умолчанию. Все должно быть ясно, когда мы посмотрим на порядок выбранных имен файлов:

4. Наследование

Another advantage of the resource bundle concept is property inheritance. It means that key-values pairs included in less specific files are inherited by those which are higher in the inheritance tree.

Let’s assume that we have three property files:

Resource bundle retrieved for Locale(“pl”, “PL”) would return all three keys/values in the result. It’s worth to mention, there’s no fall back to default locale bundle as far as property inheritance is considered.

What is more, ListResourceBundles and PropertyResourceBundles aren’t in the same hierarchy.

So if a property file is found in the classpath then key-value pairs are inherited only from property files. The same rule applies to Java files.

5. Customization

All we’ve learned above was about the default implementation of ResourceBundle. However, there’s a way we can modify its behavior.

We do this by extending ResourceBoundle.Control and overriding its methods.

For example, we can change the time of keeping values in cache or determine the condition when the cache should be reloaded.

For a better understanding, let’s prepare a short method as an example:

The purpose of this method is to change a manner of selecting files in the classpath. As we can see, ExampleControl will return only polish Locale, no matter what the default or defined Locale is.

6. UTF-8

Since there’re still many applications using JDK 8 or older versions, it’s worth to know that prior to Java 9ListResourceBundles had one more advantage over PropertyResourceBundles. As Java files can store String objects, they are able to hold any character supported by UTF-16 encoding.

On the contrary, PropertyResourceBundle loads files by default using ISO 8859-1 encoding, which has fewer characters than UTF-8 (causing problems for our Polish language examples).

In order to save characters which are beyond UTF-8, we can use the Native-To-ASCII converter – native2ascii. It converts all characters that aren’t compliant with ISO 8859-1 by encoding them to \uxxxx notation.

Here’s an example command:

And let’s see how properties look like before and after a change of encoding:

Fortunately, this inconvenience exists no longer in Java 9. JVM reads property files in UTF-8 encoding, and there’s no problem in using non-Latin characters.

7. Conclusion

BundleResource contains much of what we need to develop a multilingual application. The features we’ve covered make manipulation of different locales pretty straightforward.

Как всегда, образец кода доступен на GitHub.

Источник

Resourcebundle java что это

Каждый пакет ресурса в семействе содержит те же самые элементы, но элементы были преобразованы для локали, представленной тем пакетом ресурса. Например, у и «MyResources» и «MyResources_de» может быть a String это используется на кнопке для того, чтобы отменить операции. В «MyResources» String может содержать «Отмену», и в «MyResources_de» она может содержать «Abbrechen».

Если есть различные ресурсы для разных стран, можно сделать специализации: например, «MyResources_de_CH» содержит объекты для немецкого языка (de) в Швейцарии (CH). Если Вы хотите только изменить некоторые из ресурсов в специализации, можно сделать так.

Когда Ваша программа нуждается в специфичном для локали объекте, она загружается ResourceBundle класс используя getBundle метод:

Пакеты ресурса содержат пары ключ/значение. Ключи однозначно определяют специфичный для локали объект в пакете. Вот пример a ListResourceBundle это содержит две пары ключ/значение:

Вы получаете объект от пакета ресурса, используя соответствующий метод метода get. Поскольку «OkKey» и «CancelKey» являются оба строками, Вы использовали бы getString получать их:

ResourceBundle. Управление

Управление кэшем

Пример

Вложенная Сводка Класса

Вложенные Классы

Модификатор и ТипКласс и Описание
static classResourceBundle. Управление

Полевая Сводка

Сводка конструктора

Сводка метода

Методы

Модификатор и ТипМетод и Описание
static voidclearCache()

Методы java.lang унаследованный от класса. Объект

Полевая Деталь

родитель

Деталь конструктора

ResourceBundle

Деталь метода

getString

getStringArray

getObject

getLocale

setParent

getBundle

getBundle

getBundle

getBundle

getBundle

getBundle использует базовое имя, указанную локаль, и локаль по умолчанию (полученный из Locale.getDefault ) чтобы генерировать последовательность кандидата связывают имена. Если язык указанной локали, сценарий, страна, и разновидность являются всеми пустыми строками, то базовое имя является единственным именем пакета кандидата. Иначе, список локалей кандидата сгенерирован от значений атрибута указанной локали (язык, сценарий, страна и разновидность) и добавлен к базовому имени. Как правило, это будет похоже на следующее:

Пакет кандидата называет, где заключительный компонент является пустой строкой, опускаются, наряду с подчеркиванием. Например, если бы страна является пустой строкой, второе и пятый пакет кандидата ранее назвали, был бы опущен. Кроме того, если сценарий является пустой строкой, имена кандидата включая сценарий опускаются. Например, локаль с языком «de» и различным «JAVA» произведет имена кандидата с базовым именем «MyResource» ниже. В случае, что разновидность содержит одно или более подчеркиваний (‘ _ ‘), последовательность имен пакета, сгенерированных, усекая последнее подчеркивание и часть после него, вставляется после имени пакета кандидата с исходной разновидностью. Например, для локали с языком «en», сценарий «Latn, страна «US» и различный «WINDOWS_VISTA», и базовое имя пакета «MyResource», список имен пакета кандидата ниже сгенерирован:

Отметьте: Для некоторых Locale s, список имен пакета кандидата содержит дополнительные имена, или порядок имен пакета немного изменяется. См. описание реализации по умолчанию getCandidateLocales для деталей.

Это продолжается, пока пакет ресурса результата не инстанцируют, или список имен пакета кандидата исчерпывается. Если никакой пакет ресурса соответствия не находится, управление по умолчанию getFallbackLocale метод вызывают, который возвращает текущую локаль по умолчанию. Новая последовательность имен локали кандидата сгенерирована, используя эту локаль и и ищется снова, как выше.

Если все еще никакой пакет результата не находится, одно только базовое имя ищется. Если это все еще перестало работать, a MissingResourceException бросается.

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

Всякий раз, когда это успешно выполняется, это вызывает ранее инстанцированный пакет ресурса setParent метод с новым пакетом ресурса. Это продолжается, пока список имен не исчерпывается, или у текущего пакета уже есть ненулевой родитель.

Как только родительская цепочка полна, пакет возвращается.

Отметьте: getBundle кэши инстанцированные пакеты ресурса и могли бы возвратить тот же самый экземпляр пакета ресурса многократно.

Note:The baseName параметром должно быть полностью определенное имя класса. Однако, для совместимости с более ранними версиями, Java Sun Среды выполнения SE не проверяют это, и таким образом, это возможно к доступу PropertyResourceBundle s, определяя путь (использующий «/») вместо полностью определенного имени класса (использование «.»).

Источник

Resourcebundle java что это

Each resource bundle in a family contains the same items, but the items have been translated for the locale represented by that resource bundle. For example, both «MyResources» and «MyResources_de» may have a String that’s used on a button for canceling operations. In «MyResources» the String may contain «Cancel» and in «MyResources_de» it may contain «Abbrechen».

If there are different resources for different countries, you can make specializations: for example, «MyResources_de_CH» contains objects for the German language (de) in Switzerland (CH). If you want to only modify some of the resources in the specialization, you can do so.

When your program needs a locale-specific object, it loads the ResourceBundle class using the getBundle method:

Resource bundles contain key/value pairs. The keys uniquely identify a locale-specific object in the bundle. Here’s an example of a ListResourceBundle that contains two key/value pairs:

You retrieve an object from resource bundle using the appropriate getter method. Because «OkKey» and «CancelKey» are both strings, you would use getString to retrieve them:

The implementation of a ResourceBundle subclass must be thread-safe if it’s simultaneously used by multiple threads. The default implementations of the non-abstract methods in this class, and the methods in the direct known concrete subclasses ListResourceBundle and PropertyResourceBundle are thread-safe.

Resource Bundles and Named Modules

Resource bundles together with an application

Resource bundles as service providers

Resource bundles in other modules and class path

The getBundle factory methods with no Control parameter locate and load resource bundles from service providers. It may continue the search as if calling Module.getResourceAsStream(String) to find the named resource from a given module and calling ClassLoader.getResourceAsStream(String) ; refer to the specification of the getBundle method for details. Only non-encapsulated resource bundles of » java.class » or » java.properties » format are searched.

If the caller module is a resource bundle provider, it does not fall back to the class loader search.

Resource bundles in automatic modules

ResourceBundle.Control

ResourceBundle.Control is designed for an application deployed in an unnamed module, for example to support resource bundles in non-standard formats or package localized resources in a non-traditional convention. ResourceBundleProvider is the replacement for ResourceBundle.Control when migrating to modules. UnsupportedOperationException will be thrown when a factory method that takes the ResourceBundle.Control parameter is called.

Cache Management

Example

Nested Class Summary

Field Summary

Constructor Summary

Method Summary

Methods declared in class java.lang.Object

Field Detail

parent

Constructor Detail

ResourceBundle

Method Detail

getBaseBundleName

getString

getStringArray

getObject

getLocale

setParent

getBundle

getBundle

getBundle

getBundle

getBundle(baseName, Locale.getDefault(), module)

getBundle

If the given module is an unnamed module, then this method is equivalent to calling getBundle(baseName, targetLocale, module.getClassLoader() to load resource bundles that are visible to the class loader of the given unnamed module. Custom ResourceBundleControlProvider implementations, if present, will only be invoked if the specified module is an unnamed module.

getBundle

getBundle

When this method is called from a named module and the given loader is the class loader of the caller module, this is equivalent to calling:

getBundle uses the base name, the specified locale, and the default locale (obtained from Locale.getDefault ) to generate a sequence of candidate bundle names. If the specified locale’s language, script, country, and variant are all empty strings, then the base name is the only candidate bundle name. Otherwise, a list of candidate locales is generated from the attribute values of the specified locale (language, script, country and variant) and appended to the base name. Typically, this will look like the following:

Candidate bundle names where the final component is an empty string are omitted, along with the underscore. For example, if country is an empty string, the second and the fifth candidate bundle names above would be omitted. Also, if script is an empty string, the candidate names including script are omitted. For example, a locale with language «de» and variant «JAVA» will produce candidate names with base name «MyResource» below. In the case that the variant contains one or more underscores (‘_’), a sequence of bundle names generated by truncating the last underscore and the part following it is inserted after a candidate bundle name with the original variant. For example, for a locale with language «en», script «Latn, country «US» and variant «WINDOWS_VISTA», and bundle base name «MyResource», the list of candidate bundle names below is generated:

Note: For some Locale s, the list of candidate bundle names contains extra names, or the order of bundle names is slightly modified. See the description of the default implementation of getCandidateLocales for details.

This continues until a result resource bundle is instantiated or the list of candidate bundle names is exhausted. If no matching resource bundle is found, the default control’s getFallbackLocale method is called, which returns the current default locale. A new sequence of candidate locale names is generated using this locale and searched again, as above.

If still no result bundle is found, the base name alone is looked up. If this still fails, a MissingResourceException is thrown.

Once a result resource bundle has been found, its parent chain is instantiated. If the result bundle already has a parent (perhaps because it was returned from a cache) the chain is complete.

Otherwise, getBundle examines the remainder of the candidate locale list that was used during the pass that generated the result resource bundle. (As before, candidate bundle names where the final component is an empty string are omitted.) When it comes to the end of the candidate list, it tries the plain bundle name. With each of the candidate bundle names it attempts to instantiate a resource bundle (first looking for a class and then a properties file, as described above).

Whenever it succeeds, it calls the previously instantiated resource bundle’s setParent method with the new resource bundle. This continues until the list of names is exhausted or the current bundle already has a non-null parent.

Once the parent chain is complete, the bundle is returned.

Note: getBundle caches instantiated resource bundles and might return the same resource bundle instance multiple times.

Note:The baseName argument should be a fully qualified class name. However, for compatibility with earlier versions, Java SE Runtime Environments do not verify this, and so it is possible to access PropertyResourceBundle s by specifying a path name (using «/») instead of a fully qualified class name (using «.»).

Источник

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *