我想确定我的Java程序以编程方式运行的主机的操作系统(例如:我希望能够根据我是在Windows还是Unix平台上加载不同的属性)。100%可靠的最安全的方法是什么?
当前回答
只需使用下面的com.sun.javafx.util.Utils即可。
if ( Utils.isWindows()){
// LOGIC HERE
}
或使用
boolean isWindows = OSInfo.getOSType().equals(OSInfo.OSType.WINDOWS);
if (isWindows){
// YOUR LOGIC HERE
}
其他回答
我喜欢沃尔夫冈的回答,只是因为我相信这样的事情应该是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;
}
}
只需使用下面的com.sun.javafx.util.Utils即可。
if ( Utils.isWindows()){
// LOGIC HERE
}
或使用
boolean isWindows = OSInfo.getOSType().equals(OSInfo.OSType.WINDOWS);
if (isWindows){
// YOUR LOGIC HERE
}
你可以使用:
System.getProperty("os.name")
附注:你可能会发现这段代码很有用:
class ShowProperties {
public static void main(String[] args) {
System.getProperties().list(System.out);
}
}
它所做的就是打印出Java实现提供的所有属性。它将使您了解通过属性可以了解Java环境的哪些信息。: -)
我认为下面的内容可以用更少的字里行间覆盖更广的范围
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
以下JavaFX类有静态方法来确定当前的操作系统(isWindows(),isLinux()…):
com.sun.javafx.PlatformUtil com.sun.media.jfxmediaimpl.HostUtils com.sun.javafx.util.Utils
例子:
if (PlatformUtil.isWindows()){
...
}