Translate country name into other language

2019-09-13 10:22发布

问题:

I searched for a solution, but I have not found any.

I have this kind of information:

String locale = "en_GB";
String country = "Japonia"; //It means Japan in polish

I need to translate the country name "Japonia" into language indicated in string locale, so "Japan". Is there any way to do it?

回答1:

Assuming you know both the input language and the desired output language, an alternative approach - iterate the Locale(s) on the system using Locale.getAvailableLocales(), test if the country name matches from the desired in Locale - if so display it in the desired output Locale using getDisplayCountry(Locale)

String country = "Japonia";
Locale outLocale = Locale.forLanguageTag("en_GB");
Locale inLocale = Locale.forLanguageTag("pl-PL");
for (Locale l : Locale.getAvailableLocales()) {
    if (l.getDisplayCountry(inLocale).equals(country)) {
        System.out.println(l.getDisplayCountry(outLocale));
        break;
    }
}

Outputs

Japan

And if you modify the outLocale like

Locale outLocale = Locale.forLanguageTag("es-SP");

you get

Japón


回答2:

(Answer based on comment by Elliott Frisch)

The Java Runtime Library doesn't have a translation API, but the Locale class can be used to get the name of any country in any language, as long as you know the ISO 3166 alpha-2 country code, and the ISO 639 alpha-2 or alpha-3 language code.

Example for country Japan:

Locale countryJapan = new Locale.Builder().setRegion("JP"/*Japan*/).build();
Locale langEnglish  = new Locale.Builder().setLanguage("en"/*English*/).build();
Locale langPolish   = new Locale.Builder().setLanguage("pl"/*Polish*/).build();
Locale langJapanese = new Locale.Builder().setLanguage("ja"/*Japanese*/).build();
Locale langItalian  = new Locale.Builder().setLanguage("it"/*Italian*/).build();
System.out.println(countryJapan.getDisplayCountry(langEnglish));
System.out.println(countryJapan.getDisplayCountry(langPolish));
System.out.println(countryJapan.getDisplayCountry(langJapanese));
System.out.println(countryJapan.getDisplayCountry(langItalian));

Output

Japan
Japonia
日本
Giappone


回答3:

Yes, you can use a translation API. Like Microsoft's or Google's.



标签: java locale