如何从 Java 中的 String 表示中获取 Locale?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2522248/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get Locale from its String representation in Java?
提问by Joonas Pulakka
Is there a neat way of getting a Localeinstance from its "programmatic name" as returned by Locale's toString()
method? An obvious and ugly solution would be parsing the String and then constructing a new Locale instance according to that, but maybe there's a better way / ready solution for that?
是否有一种巧妙的方法可以从 Locale 的方法返回的“编程名称”中获取Locale实例toString()
?一个明显而丑陋的解决方案是解析 String 然后根据它构造一个新的 Locale 实例,但也许有更好的方法/现成的解决方案?
The need is that I want to store some locale specific settings in a SQL database, including Locales themselves, but it would be ugly to put serialized Locale objects there. I would rather store their String representations, which seem to be quite adequate in detail.
需要的是我想在 SQL 数据库中存储一些特定于语言环境的设置,包括语言环境本身,但是将序列化的语言环境对象放在那里会很丑陋。我宁愿存储它们的 String 表示,这在细节上似乎已经足够了。
采纳答案by raj
See the Locale.getLanguage()
, Locale.getCountry()
... Store this combination in the database instead of the "programatic name"
...
When you want to build the Locale back, use public Locale(String language, String country)
请参阅Locale.getLanguage()
, Locale.getCountry()
... 将此组合存储在数据库中而不是"programatic name"
...
当您想重新构建 Locale 时,请使用public Locale(String language, String country)
Here is a sample code :)
这是一个示例代码:)
// May contain simple syntax error, I don't have java right now to test..
// but this is a bigger picture for your algo...
public String localeToString(Locale l) {
return l.getLanguage() + "," + l.getCountry();
}
public Locale stringToLocale(String s) {
StringTokenizer tempStringTokenizer = new StringTokenizer(s,",");
if(tempStringTokenizer.hasMoreTokens())
String l = tempStringTokenizer.nextElement();
if(tempStringTokenizer.hasMoreTokens())
String c = tempStringTokenizer.nextElement();
return new Locale(l,c);
}
回答by skaffman
There doesn't seem to be a static valueOf
method for this, which is a bit surprising.
似乎没有一个静态valueOf
方法,这有点令人惊讶。
One rather ugly, but simple, way, would be to iterate over Locale.getAvailableLocales()
, comparing their toString
values with your value.
一种相当丑陋但简单的方法是迭代Locale.getAvailableLocales()
,将它们的toString
值与您的值进行比较。
Not very nice, but no string parsing required. You could pre-populate a Map
of Strings to Locales, and look up your database string in that Map.
不是很好,但不需要字符串解析。您可以将 a Map
of Strings预填充到 Locales,并在该 Map 中查找您的数据库字符串。
回答by Riduidel
Well, I would store instead a string concatenation of Locale.getISO3Language()
, getISO3Country()
and getVariant() as key, which would allow me to latter call Locale(String language, String country, String variant)
constructor.
好吧,我将存储Locale.getISO3Language()
,getISO3Country()
和 getVariant()的字符串连接作为键,这将允许我稍后调用Locale(String language, String country, String variant)
构造函数。
indeed, relying of displayLanguage implies using the langage of locale to display it, which make it locale dependant, contrary to iso language code.
事实上,依赖 displayLanguage 意味着使用语言环境的语言来显示它,这使得它依赖于语言环境,这与 iso 语言代码相反。
As an example, en locale key would be storable as
例如,en locale key 可以存储为
en_EN
en_US
and so on ...
等等 ...
回答by Tauren
Old question with plenty of answers, but here's more solutions:
有很多答案的老问题,但这里有更多解决方案:
回答by yurilo
Method that returns locale from string exists in commons-lang library:
LocaleUtils.toLocale(localeAsString)
从字符串返回语言环境的方法存在于 commons-lang 库中:
LocaleUtils.toLocale(localeAsString)
回答by Martin L.
Because I have just implemented it:
因为我刚刚实现了它:
In Groovy
/Grails
it would be:
在Groovy
/Grails
它将是:
def locale = Locale.getAvailableLocales().find { availableLocale ->
return availableLocale.toString().equals(searchedLocale)
}
回答by nilskp
Since Java 7 there is factory method Locale.forLanguageTag
and instance method Locale.toLanguageTag
using IETF language tags.
从 Java 7 开始,就有使用IETF 语言标签的工厂方法Locale.forLanguageTag
和实例方法。Locale.toLanguageTag
回答by andy
This answer may be a little late, but it turns out that parsing out the string is not as ugly as the OP assumed. I found it quite simple and concise:
这个答案可能有点晚了,但事实证明,解析出的字符串并不像 OP 假设的那样难看。我发现它非常简单明了:
public static Locale fromString(String locale) {
String parts[] = locale.split("_", -1);
if (parts.length == 1) return new Locale(parts[0]);
else if (parts.length == 2
|| (parts.length == 3 && parts[2].startsWith("#")))
return new Locale(parts[0], parts[1]);
else return new Locale(parts[0], parts[1], parts[2]);
}
I tested this (on Java 7) with all the examples given in the Locale.toString() documentation: "en", "de_DE", "_GB", "en_US_WIN", "de__POSIX", "zh_CN_#Hans", "zh_TW_#Hant-x-java", and "th_TH_TH_#u-nu-thai".
我使用 Locale.toString() 文档中给出的所有示例对此(在 Java 7 上)进行了测试:“en”、“de_DE”、“_GB”、“en_US_WIN”、“de__POSIX”、“zh_CN_#Hans”、“zh_TW_” #Hant-x-java”和“th_TH_TH_#u-nu-thai”。
IMPORTANT UPDATE: This is not recommended for use in Java 7+ according to the documentation:
重要更新:根据文档,不建议在 Java 7+ 中使用:
In particular, clients who parse the output of toString into language, country, and variant fields can continue to do so (although this is strongly discouraged), although the variant field will have additional information in it if script or extensions are present.
特别是,将 toString 的输出解析为语言、国家和变体字段的客户端可以继续这样做(尽管强烈不鼓励这样做),尽管如果存在脚本或扩展名,变体字段中将包含其他信息。
Use Locale.forLanguageTag and Locale.toLanguageTag instead, or if you must, Locale.Builder.
改用 Locale.forLanguageTag 和 Locale.toLanguageTag,或者如果必须,使用 Locale.Builder。
回答by Mygod
You can use this on Android. Works fine for me.
您可以在 Android 上使用它。对我来说很好用。
private static final Pattern localeMatcher = Pattern.compile
("^([^_]*)(_([^_]*)(_#(.*))?)?$");
public static Locale parseLocale(String value) {
Matcher matcher = localeMatcher.matcher(value.replace('-', '_'));
return matcher.find()
? TextUtils.isEmpty(matcher.group(5))
? TextUtils.isEmpty(matcher.group(3))
? TextUtils.isEmpty(matcher.group(1))
? null
: new Locale(matcher.group(1))
: new Locale(matcher.group(1), matcher.group(3))
: new Locale(matcher.group(1), matcher.group(3),
matcher.group(5))
: null;
}
回答by VdeX
Java provides lot of things with proper implementation lot of complexity can be avoided. This returns ms_MY.
String key = "ms-MY"; Locale locale = new Locale.Builder().setLanguageTag(key).build();
Apache Commons has
LocaleUtils
to help parse a string representation. This will return en_USString str = "en-US"; Locale locale = LocaleUtils.toLocale(str); System.out.println(locale.toString());
You can also use locale constructors.
// Construct a locale from a language code.(eg: en) new Locale(String language) // Construct a locale from language and country.(eg: en and US) new Locale(String language, String country) // Construct a locale from language, country and variant. new Locale(String language, String country, String variant)
Java 提供了许多具有正确实现的东西,可以避免许多复杂性。这将返回ms_MY。
String key = "ms-MY"; Locale locale = new Locale.Builder().setLanguageTag(key).build();
Apache Commons 必须
LocaleUtils
帮助解析字符串表示。这将返回en_USString str = "en-US"; Locale locale = LocaleUtils.toLocale(str); System.out.println(locale.toString());
您还可以使用区域设置构造函数。
// Construct a locale from a language code.(eg: en) new Locale(String language) // Construct a locale from language and country.(eg: en and US) new Locale(String language, String country) // Construct a locale from language, country and variant. new Locale(String language, String country, String variant)
Please check this LocaleUtilsand this Localeto explore more methods.
请检查此LocaleUtils和此Locale以探索更多方法。