How do I programmatically determine operating system in Java?

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

    TL;DR

    For accessing OS use: System.getProperty("os.name").


    But why not create a utility class, make it reusable! And probably much faster on multiple calls. Clean, clear, faster!

    Create a Util class for such utility functions. Then create public enums for each operating system type.

    public class Util {     
            public enum OS {
                WINDOWS, LINUX, MAC, SOLARIS
            };// Operating systems.
    
        private static OS os = null;
    
        public static OS getOS() {
            if (os == null) {
                String operSys = System.getProperty("os.name").toLowerCase();
                if (operSys.contains("win")) {
                    os = OS.WINDOWS;
                } else if (operSys.contains("nix") || operSys.contains("nux")
                        || operSys.contains("aix")) {
                    os = OS.LINUX;
                } else if (operSys.contains("mac")) {
                    os = OS.MAC;
                } else if (operSys.contains("sunos")) {
                    os = OS.SOLARIS;
                }
            }
            return os;
        }
    }
    

    Now, you can easily invoke class from any class as follows,(P.S. Since we declared os variable as static, it will consume time only once to identify the system type, then it can be used until your application halts. )

                switch (Util.getOS()) {
                case WINDOWS:
                    //do windows stuff
                    break;
                case LINUX:
    

    and That is it!

    0 讨论(0)
  • 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;
      }
    }
    
    0 讨论(0)
  • 2020-11-22 05:15

    I liked Wolfgang's answer, just because I believe things like that should be consts...

    so I've rephrased it a bit for myself, and thought to share it :)

    /**
     * types of Operating Systems
     *
     * please keep the note below as a pseudo-license
     *
     * helper class to check the operating system this Java VM runs in
     * 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
     */
    public enum OSType {
        MacOS("mac", "darwin"),
        Windows("win"),
        Linux("nux"),
        Other("generic");
    
        private static OSType detectedOS;
    
        private final String[] keys;
    
        private OSType(String... keys) {
            this.keys = keys;
        }
    
        private boolean match(String osKey) {
            for (int i = 0; i < keys.length; i++) {
                if (osKey.indexOf(keys[i]) != -1)
                    return true;
            }
            return false;
        }
    
        public static OSType getOS_Type() {
            if (detectedOS == null)
                detectedOS = getOperatingSystemType(System.getProperty("os.name", Other.keys[0]).toLowerCase());
            return detectedOS;
        }
    
        private static OSType getOperatingSystemType(String osKey) {
            for (OSType osType : values()) {
                if (osType.match(osKey))
                    return osType;
            }
            return Other;
        }
    }
    
    0 讨论(0)
  • 2020-11-22 05:17

    In com.sun.jna.Platform class you can find useful static methods like

    Platform.isWindows();
    Platform.is64Bit();
    Platform.isIntel();
    Platform.isARM();
    

    and much more.

    If you use Maven just add dependency

    <dependency>
     <groupId>net.java.dev.jna</groupId>
     <artifactId>jna</artifactId>
     <version>5.2.0</version>
    </dependency>
    

    Otherwise just find jna library jar file (ex. jna-5.2.0.jar) and add it to classpath.

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

    You can just use sun.awt.OSInfo#getOSType() method

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

    I think following can give broader coverage in fewer lines

    import org.apache.commons.exec.OS;
    
    if (OS.isFamilyWindows()){
                    //load some property
                }
    else if (OS.isFamilyUnix()){
                    //load some other property
                }
    

    More details here: https://commons.apache.org/proper/commons-exec/apidocs/org/apache/commons/exec/OS.html

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