Parses and returns Locale by given String local String like en_EN or de_DE. - Java java.util

Java examples for java.util:ResourceBundle

Description

Parses and returns Locale by given String local String like en_EN or de_DE.

Demo Code


import java.util.IllegalFormatException;
import java.util.Locale;
import java.util.MissingResourceException;
import java.util.ResourceBundle;
import org.apache.log4j.Logger;

public class Main{

    /**/*from   w  ww .  j  av a  2s.  c  o m*/
     * Parses and returns Locale by given String local String like <code>en_EN</code> or <code>de_DE</code>.
     * 
     * @return Locale
     */
    public static Locale getLocale(String localString)
            throws IllegalArgumentException {
        Locale ret;

        String[] locstr = localString.split("_");
        switch (locstr.length) {
        case 1:
            ret = new Locale(locstr[0]);
            break;
        case 2:
            ret = new Locale(locstr[0], locstr[1]);
            break;
        case 3:
            ret = new Locale(locstr[0], locstr[1], locstr[2]);
            break;
        default:
            throw new IllegalArgumentException(
                    "Could not parse locale from string: " + localString);
        }

        return ret;

    }
}

Related Tutorials