How do I programmatically determine operating system in Java?

后端 未结 19 2880
眼角桃花
眼角桃花 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:15

    some of the links in the answers above seem to be broken. I have added pointers to current source code in the code below and offer an approach for handling the check with an enum as an answer so that a switch statement can be used when evaluating the result:

    OsCheck.OSType ostype=OsCheck.getOperatingSystemType();
    switch (ostype) {
        case Windows: break;
        case MacOS: break;
        case Linux: break;
        case Other: break;
    }
    

    The helper class is:

    /**
     * helper class to check the operating system this Java VM runs in
     *
     * please keep the notes below as a pseudo-license
     *
     * http://stackoverflow.com/questions/228477/how-do-i-programmatically-determine-operating-system-in-java
     * compare to http://svn.terracotta.org/svn/tc/dso/tags/2.6.4/code/base/common/src/com/tc/util/runtime/Os.java
     * http://www.docjar.com/html/api/org/apache/commons/lang/SystemUtils.java.html
     */
    import java.util.Locale;
    public static final class OsCheck {
      /**
       * types of Operating Systems
       */
      public enum OSType {
        Windows, MacOS, Linux, Other
      };
    
      // cached result of OS detection
      protected static OSType detectedOS;
    
      /**
       * detect the operating system from the os.name System property and cache
       * the result
       * 
       * @returns - the operating system detected
       */
      public static OSType getOperatingSystemType() {
        if (detectedOS == null) {
          String OS = System.getProperty("os.name", "generic").toLowerCase(Locale.ENGLISH);
          if ((OS.indexOf("mac") >= 0) || (OS.indexOf("darwin") >= 0)) {
            detectedOS = OSType.MacOS;
          } else if (OS.indexOf("win") >= 0) {
            detectedOS = OSType.Windows;
          } else if (OS.indexOf("nux") >= 0) {
            detectedOS = OSType.Linux;
          } else {
            detectedOS = OSType.Other;
          }
        }
        return detectedOS;
      }
    }
    

提交回复
热议问题