How do I programmatically determine operating system in Java?

后端 未结 19 2521
眼角桃花
眼角桃花 2020-11-22 04:56

I would like to determine the operating system of the host that my Java program is running programmatically (for example: I would like to be able to load different propertie

相关标签:
19条回答
  • 2020-11-22 05:25

    If you're interested in how an open source project does stuff like this, you can check out the Terracotta class (Os.java) that handles this junk here:

    • http://svn.terracotta.org/svn/tc/dso/trunk/code/base/common/src/com/tc/util/runtime/
    • http://svn.terracotta.org/svn/tc/dso/tags/2.6.4/code/base/common/src/com/tc/util/runtime/

    And you can see a similar class to handle JVM versions (Vm.java and VmVersion.java) here:

    • http://svn.terracotta.org/svn/tc/dso/trunk/common/src/main/java/com/tc/util/runtime/
    0 讨论(0)
  • 2020-11-22 05:27

    Just use com.sun.javafx.util.Utils as below.

    if ( Utils.isWindows()){
         // LOGIC HERE
    }
    

    OR USE

    boolean isWindows = OSInfo.getOSType().equals(OSInfo.OSType.WINDOWS);
           if (isWindows){
             // YOUR LOGIC HERE
           }
    
    0 讨论(0)
  • 2020-11-22 05:28

    I find that the OS Utils from Swingx does the job.

    0 讨论(0)
  • 2020-11-22 05:29

    Oct. 2008:

    I would recommend to cache it in a static variable:

    public static final class OsUtils
    {
       private static String OS = null;
       public static String getOsName()
       {
          if(OS == null) { OS = System.getProperty("os.name"); }
          return OS;
       }
       public static boolean isWindows()
       {
          return getOsName().startsWith("Windows");
       }
    
       public static boolean isUnix() // and so on
    }
    

    That way, every time you ask for the Os, you do not fetch the property more than once in the lifetime of your application.


    February 2016: 7+ years later:

    There is a bug with Windows 10 (which did not exist at the time of the original answer).
    See "Java's “os.name” for Windows 10?"

    0 讨论(0)
  • 2020-11-22 05:30

    As indicated in other answers, System.getProperty provides the raw data. However, the Apache Commons Lang component provides a wrapper for java.lang.System with handy properties like SystemUtils.IS_OS_WINDOWS, much like the aforementioned Swingx OS util.

    0 讨论(0)
  • 2020-11-22 05:31
    String osName = System.getProperty("os.name");
    System.out.println("Operating system " + osName);
    
    0 讨论(0)
提交回复
热议问题