我想确定我的Java程序以编程方式运行的主机的操作系统(例如:我希望能够根据我是在Windows还是Unix平台上加载不同的属性)。100%可靠的最安全的方法是什么?


当前回答

你可以使用sun.awt.OSInfo#getOSType()方法

其他回答

我认为下面的内容可以用更少的字里行间覆盖更广的范围

import org.apache.commons.exec.OS;

if (OS.isFamilyWindows()){
                //load some property
            }
else if (OS.isFamilyUnix()){
                //load some other property
            }

更多详情请访问:https://commons.apache.org/proper/commons-exec/apidocs/org/apache/commons/exec/OS.html

你可以使用:

System.getProperty("os.name")

附注:你可能会发现这段代码很有用:

class ShowProperties {
    public static void main(String[] args) {
        System.getProperties().list(System.out);
    }
}

它所做的就是打印出Java实现提供的所有属性。它将使您了解通过属性可以了解Java环境的哪些信息。: -)

试试这个,简单易行

System.getProperty("os.name");
System.getProperty("os.version");
System.getProperty("os.arch");

下面是一些简短、简洁(并且热切地计算过)的顶级答案:

switch(OSType.DETECTED){
...
}

helper enum:

public enum OSType {
    Windows, MacOS, Linux, Other;
    public static final  OSType DETECTED;
    static{
        String OS = System.getProperty("os.name", "generic").toLowerCase(Locale.ENGLISH);
        if ((OS.contains("mac")) || (OS.contains("darwin"))) {
            DETECTED = OSType.MacOS;
        } else if (OS.contains("win")) {
            DETECTED = OSType.Windows;
        } else if (OS.contains("nux")) {
            DETECTED = OSType.Linux;
        } else {
            DETECTED = OSType.Other;
        }
    }
}

2008年10月:

我建议将它缓存到一个静态变量中:

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
}

这样,每次请求o时,在应用程序的生命周期内只获取一次属性。


2016年2月:7年多后:

Windows 10有一个错误(在最初的答案时不存在)。 参见“Java的“os.name”for Windows 10?”