如何使用Java编程确定操作系统?

626

我想通过编程方式确定我的Java程序正在运行的主机操作系统(例如:我希望能够根据是否在Windows或Unix平台上加载不同的属性)。有没有一种百分之百可靠的安全方法可以做到这一点?

22个回答

9
以下代码展示了您可以从系统API中获取的值,这些值都可以通过此API获得。
public class App {
    public static void main( String[] args ) {
        //Operating system name
        System.out.println(System.getProperty("os.name"));

        //Operating system version
        System.out.println(System.getProperty("os.version"));

        //Path separator character used in java.class.path
        System.out.println(System.getProperty("path.separator"));

        //User working directory
        System.out.println(System.getProperty("user.dir"));

        //User home directory
        System.out.println(System.getProperty("user.home"));

        //User account name
        System.out.println(System.getProperty("user.name"));

        //Operating system architecture
        System.out.println(System.getProperty("os.arch"));

        //Sequence used by operating system to separate lines in text files
        System.out.println(System.getProperty("line.separator"));

        System.out.println(System.getProperty("java.version")); //JRE version number

        System.out.println(System.getProperty("java.vendor.url")); //JRE vendor URL

        System.out.println(System.getProperty("java.vendor")); //JRE vendor name

        System.out.println(System.getProperty("java.home")); //Installation directory for Java Runtime Environment (JRE)

        System.out.println(System.getProperty("java.class.path"));

        System.out.println(System.getProperty("file.separator"));
    }
}

答案:

Windows 7
6.1
;
C:\Users\user\Documents\workspace-eclipse\JavaExample
C:\Users\user
user
amd64


1.7.0_71
http://java.oracle.com/
Oracle Corporation
C:\Program Files\Java\jre7
C:\Users\user\Documents\workspace-Eclipse\JavaExample\target\classes
\

9

7

以下是最佳答案的简短、清晰且计算速度更快的版本:

switch(OSType.DETECTED){
...
}

辅助枚举类型:

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

答案就是 System.getProperty("os.name")。没有人想要做这么多额外的工作。为什么要费这个劲呢? - pabrams

6

2
上述链接似乎已经失效,可能是由于SwingX引入了分支导致的;1.6版本在这里:https://swingx.dev.java.net/source/browse/swingx/tags/SwingX-1-6/src/java/org/jdesktop/swingx/util/OS.java?view=markup - David Moles
1
@David Moles,谢谢。当我回答时链接是好的 - 我现在已经用你的更新了它。 - Richard Harrison
2
最新版本在这里:http://java.net/projects/swingx/sources/svn/content/trunk/swingx-core/src/main/java/org/jdesktop/swingx/util/Utilities.java - Vladislav Rastrusny
Oracle关闭了java.net网站,因此有关心的人应该编辑此答案以修复链接。 - MarkHu
我在这里找到了一个版本:https://github.com/tmyroadctfig/swingx/blob/master/swingx-common/src/main/java/org/jdesktop/swingx/util/OS.java - 感谢@MarkHu通知我链接失效。 - Richard Harrison

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

3

我喜欢Wolfgang的回答,因为我认为这样的事情应该是常量...

所以我为自己重新表达了一下,并想分享一下 :)

/**
 * 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
 * https://dev59.com/VnVC5IYBdhLWcg3woSxW
 * 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;
    }
}

似乎“darwin”永远无法匹配,因为检查“win”就已经会返回Windows。 - tvkanters
请修正我的原始答案。 - Wolfgang Fahl
3
恭喜你,你已重新实现了 sun.awt.OSInfo#getOSType :) - Kirill Gamazkov
1
好的... @Kirill Gamazkov 我当时没找到它... 感谢你指出。 - TacB0sS

3
您可以使用sun.awt.OSInfo#getOSType()方法。

这应该是最好的答案!我只是在检查是否有人已经在这里提到过这个。 - Martin Krajčírovič
有没有绕过这个“受限API”的方法?我想尝试使用它,但在Eclipse中它会给我警告。我可以使用旧的jre(例如jre1.8.0_171),但最新的1.8 jres将其标记为受限制的。 - Brian_Entei
整个“sun”包已被弃用,我无法想象如何解决这个问题。看起来只需要使用System.getProperty("os.name"),然后检查该属性是否包含“Windows”,“Linux”,“Solaris”或“OS X”,因此基本上与Vishal Chaudhari的答案相同。 - Kirill Gamazkov

2

这段代码用于显示关于系统操作系统类型、名称、Java信息等所有信息。

public static void main(String[] args) {
    // TODO Auto-generated method stub
    Properties pro = System.getProperties();
    for(Object obj : pro.keySet()){
        System.out.println(" System  "+(String)obj+"     :  "+System.getProperty((String)obj));
    }
}

0
在com.sun.jna.Platform类中,你可以找到一些有用的静态方法。
Platform.isWindows();
Platform.is64Bit();
Platform.isIntel();
Platform.isARM();

还有更多。

如果您使用Maven,只需添加依赖项

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

否则,只需找到jna库的jar文件(例如jna-5.2.0.jar),并将其添加到类路径中。

-1

由于谷歌将“kotlin os name”指向了这个页面,这里是@Memin的答案的Kotlin版本:

private var _osType: OsTypes? = null
val osType: OsTypes
    get() {
        if (_osType == null) {
            _osType = with(System.getProperty("os.name").lowercase(Locale.getDefault())) {
                if (contains("win"))
                    OsTypes.WINDOWS
                else if (listOf("nix", "nux", "aix").any { contains(it) })
                    OsTypes.LINUX
                else if (contains("mac"))
                    OsTypes.MAC
                else if (contains("sunos"))
                    OsTypes.SOLARIS
                else
                    OsTypes.OTHER
            }
        }
        return _osType!!
    }

enum class OsTypes {
    WINDOWS, LINUX, MAC, SOLARIS, OTHER
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接