how to detect operating system language (locale) from java code

后端 未结 4 556
小鲜肉
小鲜肉 2020-11-30 03:09

What is the correct way of knowing operating system language (locale) from java code?

I have tried

Locale.getDefault()
System.getProperties(\"user.l         


        
相关标签:
4条回答
  • 2020-11-30 03:40

    To be precise, you can try following code:

    public Locale getLocale() {
        if (this.locale == null) {
            this.locale = new Locale(System.getProperty("user.language"), System.getProperty("user.country"));
        }
        return this.locale;
    }
    
    0 讨论(0)
  • 2020-11-30 03:57

    The Windows XP systeminfo command displays lots of stuff, but the relevant information is this:

    System Locale:             en-us;English (United States)
    Input Locale:              en-us;English (United States)
    

    To get equivalent information in Java, use Locale.getDefault() to get the Locale that Java is using, and use methods on the Locale object such as getCountry(), getLanguage() to get details. The information is available using ISO codes and as human readable/displayable names.

    Note that Locale.getDefault() gives you the locale that Java picks up from the environment when it starts, this may or may not be the same as the "system" locale. To definitively get the "system" locale in Java you would need to do platform specific things. IMO, it is simpler to make sure that Java gets started with the system locale ... if you really need that information.


    UPDATE: Apparently, Java 7 has changed the way that the locale information used by getDefault() is determined on Windows; see https://stackoverflow.com/a/8319889/139985

    0 讨论(0)
  • 2020-11-30 03:57

    What about

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

    Returns in my case

    user.country=DE

    user.language=de

    You easily can generate the locale from this information. Local is 'language'_'country' so in my case de_DE

    0 讨论(0)
  • 2020-11-30 04:00

    How about using the default locale?

    Locale locale = Locale.getDefault();
    String lang = locale.getDisplayLanguage();
    String country = locale.getDisplayCountry();
    

    This returns me my current language and country as per the Windows systeminfo command. Is this what you're looking for? (If you want the 2-character codes for language/country, you can just use getLanguage() or getCountry()).

    0 讨论(0)
提交回复
热议问题