Search code examples
javalocaleisoiso-639-2

Converting language names to ISO 639 language codes


I need to convert language names like 'Hungarian', 'English' to ISO 639 codes. ISO 639-6 would be the best but ISO 639-2 is good enough. What's the best way to achieve this?

I should convert the English to locale and get the language with getLanguage()? If thats the only way how can I convert a string like 'English' to a java locale?

My goal is to store book language info using the ISO 639 codes.


Solution

  • You can get a list of ISO 639-2 codes by passing a regular expression of language names to LanguageAlpha3Code.findByName(String) (in nv-i18n library).

    The following example code is a command-line tool that converts given language names into corresponding ISO 639-2 codes.

    import java.util.List;
    import com.neovisionaries.i18n.LanguageAlpha3Code;
    
    public class To639_2
    {
        public static void main(String[] args)
        {
            // For each language name given on the command line.
            for (String languageName : args)
            {
                // Get a list of ISO 639-2 codes (alpha-3 codes)
                // whose language name matches the given pattern.
                List<LanguageAlpha3Code> list
                    = LanguageAlpha3Code.findByName(languageName);
    
                // Print the language and the ISO 639-2 code.
                System.out.format("%s => %s\n", languageName,
                    (list.size() != 0) ? list.get(0) : "");
            }
        }
    }
    

    A sample execution:

    $ java -cp nv-i18n-1.14.jar:. To639_2 Hungarian English
    Hungarian => hun
    English => eng