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


当前回答

以下JavaFX类有静态方法来确定当前的操作系统(isWindows(),isLinux()…):

com.sun.javafx.PlatformUtil com.sun.media.jfxmediaimpl.HostUtils com.sun.javafx.util.Utils

例子:

if (PlatformUtil.isWindows()){
           ...
}

其他回答

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

如其他答案所示,系统。getProperty提供原始数据。然而,Apache Commons Lang组件为java.lang.System提供了一个包装器,它具有SystemUtils等方便的属性。IS_OS_WINDOWS,很像前面提到的Swingx OS util。

获取操作系统名称,只需使用:

Platform.getOS()

假设你想看看平台是否是linux:

if (Platform.getOS().equals(Platform.OS_LINUX)) {
}

类似地,Platform类为其他操作系统名称定义了常量。平台类是org.eclipse.core.runtime包的一部分。

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

如果你对一个开源项目是如何做这些事情感兴趣,你可以看看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/