Java의 문자열 표현에서 로케일을 얻는 방법은 무엇입니까?
Locale의 메서드에 의해 반환되는 "프로그램 이름"에서 Locale 인스턴스를 가져 오는 깔끔한 방법이 toString()
있습니까? 명백하고 추악한 해결책은 String을 파싱 한 다음 그에 따라 새로운 Locale 인스턴스를 구성하는 것입니다.하지만 더 나은 방법 / 준비된 솔루션이있을 수 있습니까?
로케일 자체를 포함하여 SQL 데이터베이스에 일부 로케일 특정 설정을 저장하고 싶지만 직렬화 된 Locale 객체를 거기에 두는 것은 추악합니다. 나는 차라리 상세하게 꽤 적절한 것처럼 보이는 그들의 String 표현을 저장하고 싶습니다.
참고 항목 Locale.getLanguage()
, Locale.getCountry()
대신의 데이터베이스에이 조합을 저장 ... "programatic name"
...
당신이 로케일 등을 구축하고자 할 때 사용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);
}
문자열에서 로케일을 반환하는 메서드는 commons-lang 라이브러리에 있습니다. LocaleUtils.toLocale(localeAsString)
Java 7부터는 IETF 언어 태그를 사용하는 팩토리 메소드 Locale.forLanguageTag
와 인스턴스 메소드가 있습니다 .Locale.toLanguageTag
Java는 적절한 구현으로 많은 것을 제공하므로 많은 복잡성을 피할 수 있습니다. 이것은 ms_MY를 반환합니다 .
String key = "ms-MY"; Locale locale = new Locale.Builder().setLanguageTag(key).build();
Apache Commons는
LocaleUtils
문자열 표현의 구문 분석을 도와야합니다. en_US 를 반환합니다.String 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)
더 많은 방법을 탐색 하려면이 LocaleUtils 및이 로케일 을 확인하십시오 .
이 대답은 약간 늦을 수 있지만 문자열을 구문 분석하는 것은 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".
IMPORTANT UPDATE: This is not recommended for use in Java 7+ according to the documentation:
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.
Use Locale.forLanguageTag and Locale.toLanguageTag instead, or if you must, Locale.Builder.
Option 1 :
org.apache.commons.lang3.LocaleUtils.toLocale("en_US")
Option 2 :
Locale.forLanguageTag("en-US")
Please note Option 1 is "underscore" between language and country , and Option 2 is "dash".
Old question with plenty of answers, but here's more solutions:
If you are using Spring framework in your project you can also use:
org.springframework.util.StringUtils.parseLocaleString("en_US");
Parse the given String representation into a Locale
There doesn't seem to be a static valueOf
method for this, which is a bit surprising.
One rather ugly, but simple, way, would be to iterate over Locale.getAvailableLocales()
, comparing their toString
values with your value.
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.
You can use this on Android. Works fine for me.
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;
}
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.
indeed, relying of displayLanguage implies using the langage of locale to display it, which make it locale dependant, contrary to iso language code.
As an example, en locale key would be storable as
en_EN
en_US
and so on ...
Because I have just implemented it:
In Groovy
/Grails
it would be:
def locale = Locale.getAvailableLocales().find { availableLocale ->
return availableLocale.toString().equals(searchedLocale)
}
참고URL : https://stackoverflow.com/questions/2522248/how-to-get-locale-from-its-string-representation-in-java
'IT story' 카테고리의 다른 글
UIButton 텍스트 변경 (0) | 2020.08.22 |
---|---|
요소의 XSLT 이름이 있습니까? (0) | 2020.08.22 |
자바의 현재 시간 (마이크로 초) (0) | 2020.08.22 |
localStorage의 크기를 찾는 방법 (0) | 2020.08.22 |
서비스의 Android 업데이트 활동 UI (0) | 2020.08.22 |