Parse the given localeString into a java.util.Locale : Locale « I18N « Java

Java
1. 2D Graphics GUI
2. 3D
3. Advanced Graphics
4. Ant
5. Apache Common
6. Chart
7. Class
8. Collections Data Structure
9. Data Type
10. Database SQL JDBC
11. Design Pattern
12. Development Class
13. EJB3
14. Email
15. Event
16. File Input Output
17. Game
18. Generics
19. GWT
20. Hibernate
21. I18N
22. J2EE
23. J2ME
24. JDK 6
25. JNDI LDAP
26. JPA
27. JSP
28. JSTL
29. Language Basics
30. Network Protocol
31. PDF RTF
32. Reflection
33. Regular Expressions
34. Scripting
35. Security
36. Servlets
37. Spring
38. Swing Components
39. Swing JFC
40. SWT JFace Eclipse
41. Threads
42. Tiny Application
43. Velocity
44. Web Services SOA
45. XML
Java Tutorial
Java Source Code / Java Documentation
Java Open Source
Jar File Download
Java Articles
Java Products
Java by API
Photoshop Tutorials
Maya Tutorials
Flash Tutorials
3ds-Max Tutorials
Illustrator Tutorials
GIMP Tutorials
C# / C Sharp
C# / CSharp Tutorial
C# / CSharp Open Source
ASP.Net
ASP.NET Tutorial
JavaScript DHTML
JavaScript Tutorial
JavaScript Reference
HTML / CSS
HTML CSS Reference
C / ANSI-C
C Tutorial
C++
C++ Tutorial
Ruby
PHP
Python
Python Tutorial
Python Open Source
SQL Server / T-SQL
SQL Server / T-SQL Tutorial
Oracle PL / SQL
Oracle PL/SQL Tutorial
PostgreSQL
SQL / MySQL
MySQL Tutorial
VB.Net
VB.Net Tutorial
Flash / Flex / ActionScript
VBA / Excel / Access / Word
XML
XML Tutorial
Microsoft Office PowerPoint 2007 Tutorial
Microsoft Office Excel 2007 Tutorial
Microsoft Office Word 2007 Tutorial
Java » I18N » LocaleScreenshots 
Parse the given localeString into a java.util.Locale
 
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.StringTokenizer;

/*
 * JBoss, Home of Professional Open Source
 * Copyright 2005, JBoss Inc., and individual contributors as indicated
 * by the @authors tag. See the copyright.txt in the distribution for a
 * full listing of individual contributors.
 *
 * This is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License as
 * published by the Free Software Foundation; either version 2.1 of
 * the License, or (at your option) any later version.
 *
 * This software is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this software; if not, write to the Free
 * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
 * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
 */

public class Main {

  /**
   * Parse the given localeString into a {@link java.util.Locale}.
   
   * This is the inverse operation of
   {@link java.util.Locale#toString Locale's toString}.
   
   @param localeString
   *          the locale string
   @return a corresponding Locale instance
   */
  public static Locale parseLocaleString(String localeString) {
    String[] parts = tokenizeToStringArray(localeString, "_ ", false, false);
    String language = (parts.length > ? parts[0"");
    String country = (parts.length > ? parts[1"");
    String variant = "";
    if (parts.length >= 2) {
      // There is definitely a variant, and it is everything after the country
      // code sans the separator between the country code and the variant.
      int endIndexOfCountryCode = localeString.indexOf(country+ country.length();
      // Strip off any leading '_' and whitespace, what's left is the variant.
      variant = trimLeadingWhitespace(localeString.substring(endIndexOfCountryCode));
      if (variant.startsWith("_")) {
        variant = trimLeadingCharacter(variant, '_');
      }
    }
    return (language.length() new Locale(language, country, variantnull);
  }

  /**
   * Tokenize the given String into a String array via a StringTokenizer.
   
   * The given delimiters string is supposed to consist of any number of
   * delimiter characters. Each of those characters can be used to separate
   * tokens. A delimiter is always a single character; for multi-character
   * delimiters, consider using delimitedListToStringArray
   
   @param str
   *          the String to tokenize
   @param delimiters
   *          the delimiter characters, assembled as String (each of those
   *          characters is individually considered as delimiter)
   @param trimTokens
   *          trim the tokens via String's trim
   @param ignoreEmptyTokens
   *          omit empty tokens from the result array (only applies to tokens
   *          that are empty after trimming; StringTokenizer will not consider
   *          subsequent delimiters as token in the first place).
   @return an array of the tokens (null if the input String was null)
   */
  public static String[] tokenizeToStringArray(String str, String delimiters, boolean trimTokens,
      boolean ignoreEmptyTokens) {
    if (str == null) {
      return null;
    }
    StringTokenizer st = new StringTokenizer(str, delimiters);
    List<String> tokens = new ArrayList<String>();
    while (st.hasMoreTokens()) {
      String token = st.nextToken();
      if (trimTokens) {
        token = token.trim();
      }
      if (!ignoreEmptyTokens || token.length() 0) {
        tokens.add(token);
      }
    }
    return tokens.toArray(new String[tokens.size()]);
  }

  /**
   * Trim leading whitespace from the given String.
   
   @param str
   *          the string to check
   @return the trimmed String
   @see java.lang.Character#isWhitespace(char)
   */
  public static String trimLeadingWhitespace(String str) {
    return trimLeadingCharacter(str, CharacterChecker.WHITESPACE);
  }

  /**
   * Trim all occurences of the supplied leading character from the given
   * String.
   
   @param str
   *          the string to check
   @param leadingCharacter
   *          the leading character to be trimmed
   @return the trimmed String
   */
  public static String trimLeadingCharacter(String str, final char leadingCharacter) {
    return trimLeadingCharacter(str, new CharacterChecker() {
      public boolean isCharacterLegal(char character) {
        return character == leadingCharacter;
      }
    });
  }

  /**
   * Trim all occurences of the supplied leading character from the given
   * String.
   
   @param str
   *          the string to check
   @param checker
   *          the character checker
   @return the trimmed String
   */
  public static String trimLeadingCharacter(String str, CharacterChecker checker) {
    if (hasLength(str== false) {
      return str;
    }

    if (checker == null)
      throw new IllegalArgumentException("Null character checker");

    StringBuffer buf = new StringBuffer(str);
    while (buf.length() && checker.isCharacterLegal(buf.charAt(0))) {
      buf.deleteCharAt(0);
    }
    return buf.toString();
  }

  /**
   * Check that the given string param is neither null nor of length 0.
   
   @param string
   *          the string
   @return true if the String is not null and has length
   */
  public static boolean hasLength(String string) {
    return (string != null && string.length() 0);
  }

}

   
  
Related examples in the same category
1. List Locales from Locale.getAvailableLocales()List Locales from Locale.getAvailableLocales()
2. List all Locale from SimpleDateFormatList all Locale from SimpleDateFormat
3. Locale Constant
4. Country Language CodesCountry Language Codes
5. Get Days Of The Week for different localeGet Days Of The Week for different locale
6. Get Display Country for default localeGet Display Country for default locale
7. Get ISO3 Language for default localeGet ISO3 Language for default locale
8. Get Display Name for default localeGet Display Name for default locale
9. Get Display Variant for default localeGet Display Variant for default locale
10. Get the 2-letter country code; may be equal to ""
11. List Locale OrientationList Locale Orientation
12. Get localized name suitable for display to the user
13. Setting the Default Locale on the command line
14. Set language and country code on the command line
15. Change the default locale is to call Locale.setDefault():
16. Set the default locale to pre-defined locale
17. Set the default locale to custom locale
18. format date for a Locale
19. Get a list of country names
20. Set only language code on the command line
21. Set a default Locale
22. Disable localization
23. Set of convenience routines for internationalized code
24. Print the default locale
25. Change the default locale
26. iso639-2-language-code.csv
27. iso3166-country-codes.csv
28. Converts a String to a Locale
29. Converts the double value to locale-independent string representation
30. Calculate the postfix to append to a filename to load the correct single filename for that Locale.
31. Calculate the postfixes along the search path from the base bundle to the bundle specified by baseName and locale.
32. Concat postfix to the name. Take care of existing filename extension.
33. Convert a string based locale into a Locale Object
34. Obtains an unmodifiable set of installed locales.
35. Obtains the list of languages supported for a given country.
36. Obtains the list of locales to search through when performing a locale search.
37. Returns the parent locale of a given locale.
www.java2java.com | Contact Us
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.