Skip to content
Advertisement

How to get Locale from its String representation in Java?

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?

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.

Advertisement

Answer

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)

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);
}
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement