0
点赞
收藏
分享

微信扫一扫

如何以编程方式确定Java的操作系统?


如何以编程方式确定Java的操作系统?

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

高分回答:

您可以使用:

System.getProperty("os.name")

PS:您可能会发现此代码有用:

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

高分回答:

上面答案中的某些链接似乎已断开。我在下面的代码中添加了指向当前源代码的指针,并提供了一种使用枚举作为答案来处理检查的方法,以便在评估结果时可以使用switch语句:

OsCheck.OSType ostype=OsCheck.getOperatingSystemType();
switch (ostype) {
case Windows: break;
case MacOS: break;
case Linux: break;
case Other: break;
}

助手类是:

/**
* helper class to check the operating system this Java VM runs in
*
* please keep the notes below as a pseudo-license
*
* 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
*/
import java.util.Locale;
public static final class OsCheck {
/**
* types of Operating Systems
*/
public enum OSType {
Windows, MacOS, Linux, Other
};

// cached result of OS detection
protected static OSType detectedOS;

/**
* detect the operating system from the os.name System property and cache
* the result
*
* @returns
public static OSType getOperatingSystemType() {
if (detectedOS == null) {
String OS = System.getProperty("os.name", "generic").toLowerCase(Locale.ENGLISH);
if ((OS.indexOf("mac") >= 0) || (OS.indexOf("darwin") >= 0)) {
detectedOS = OSType.MacOS;
} else if (OS.indexOf("win") >= 0) {
detectedOS = OSType.Windows;
} else if (OS.indexOf("nux") >= 0) {
detectedOS = OSType.Linux;
} else {
detectedOS = OSType.Other;
}
}
return


举报

相关推荐

0 条评论