首页 > 解决方案 > 有没有办法获得国家 ISO-2 代码,但从 Windows 属性,而不是从 JVM

问题描述

基本上如标题所述,我已经尝试过:

Locale currentLocale = Locale.getDefault();
System.out.println(currentLocale.getDisplayLanguage());
System.out.println(currentLocale.getDisplayCountry());

System.out.println(currentLocale.getLanguage());
System.out.println(currentLocale.getCountry());

System.out.println(System.getProperty("user.country"));
System.out.println(System.getProperty("user.language"));

当我在寡妇设置中设置了完全不同的东西时,这一切都给了我美国或英语。请给我任何建议。所以我希望得到 Contry 代码,例如,如果我在系统中设置了波兰,我期望“PL”但我得到“US”

标签: javawindowsjvmlocale

解决方案


默认 Java 语言环境不必与系统语言环境相同,因为它可以被覆盖

  • 具有user.country和系统属性user.languageuser.variant
  • 通过调用Locale.setDefault().

有用于获取操作系统提供的语言环境信息的非标准未记录 API。它在 Windows Vista 或更高版本上实现。试试下面的代码片段。

import sun.util.locale.provider.HostLocaleProviderAdapter;

...

    static String getHostCountry() {
        for (Locale locale : new HostLocaleProviderAdapter().getAvailableLocales()) {
            if (!locale.getCountry().isEmpty()) {
                return locale.getCountry();
            }
        }
        return null;
    }

推荐阅读