如何从Java中的String表示中获取Locale? [英] How to get Locale from its String representation in Java?
问题描述
是否有一种巧妙的方法来获取区域设置来自其程序化名称的实例,由Locale的 toString()
方法返回?一个明显而丑陋的解决方案是解析String然后根据它构建一个新的Locale实例,但也许有更好的方法/就绪解决方案呢?
Is there a neat way of getting a Locale instance 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?
需求是我想在SQL数据库中存储一些特定于语言环境的设置,包括Locales本身,但将序列化的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.
推荐答案
参见 Locale.getLanguage()
, Locale.getCountry()
...将此组合存储在数据库中而不是中编程名称
...
如果要重新构建Locale,请使用 public Locale(String language,String country)
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)
以下是示例代码:)
// 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);
}
这篇关于如何从Java中的String表示中获取Locale?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!