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


当前回答

我喜欢沃尔夫冈的回答,只是因为我相信这样的事情应该是consts……

所以我把它重新措辞了一下,并想分享一下:)

/**
 * 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;
    }
}

其他回答

如果你对一个开源项目是如何做这些事情感兴趣,你可以看看Terracotta类(Os.java)在这里处理这些垃圾:

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/

你可以在这里看到类似的类来处理JVM版本(Vm.java和VmVersion.java):

http://svn.terracotta.org/svn/tc/dso/trunk/common/src/main/java/com/tc/util/runtime/

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

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

String osName = System.getProperty("os.name");
System.out.println("Operating system " + osName);

我发现Swingx的操作系统Utils可以完成这项工作。

试试这个,简单易行

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