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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/228477/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 11:45:17  来源:igfitidea点击:

How do I programmatically determine operating system in Java?

javaoperating-system

提问by karlgrz

I would like to determine the operating system of the host that my Java program is running programmatically (for example: I would like to be able to load different properties based on whether I am on a Windows or Unix platform). What is the safest way to do this with 100% reliability?

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

采纳答案by Chris Jester-Young

You can use:

您可以使用:

System.getProperty("os.name")

P.S. You may find this code useful:

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

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

All it does is print out all the properties provided by your Java implementations. It'll give you an idea of what you can find out about your Java environment via properties. :-)

它所做的只是打印出 Java 实现提供的所有属性。它将让您了解可以通过属性找到有关 Java 环境的信息。:-)

回答by VonC

Oct. 2008:

2008 年 10 月:

I would recommend to cache it in a static variable:

我建议将它缓存在一个静态变量中:

public static final class OsUtils
{
   private static String OS = null;
   public static String getOsName()
   {
      if(OS == null) { OS = System.getProperty("os.name"); }
      return OS;
   }
   public static boolean isWindows()
   {
      return getOsName().startsWith("Windows");
   }

   public static boolean isUnix() // and so on
}

That way, every time you ask for the Os, you do not fetch the property more than once in the lifetime of your application.

这样,每次请求 Os 时,在应用程序的生命周期中不会多次获取该属性。



February 2016: 7+ years later:

2016 年 2 月:7 年后:

There is a bug with Windows 10 (which did not exist at the time of the original answer).
See "Java's “os.name” for Windows 10?"

Windows 10 存在一个错误(在原始答案时不存在)。
请参阅“适用于 Windows 10 的 Java 的“os.name”?

回答by Alex Miller

If you're interested in how an open source project does stuff like this, you can check out the Terracotta class (Os.java) that handles this junk here:

如果您对开源项目如何做这样的事情感兴趣,您可以在此处查看处理这些垃圾的 Terracotta 类 (Os.java):

And you can see a similar class to handle JVM versions (Vm.java and VmVersion.java) here:

您可以在此处看到一个类似的类来处理 JVM 版本(Vm.java 和 VmVersion.java):

回答by Richard Harrison

I find that the OS Utils from Swingxdoes the job.

我发现SwingxOS Utils 可以完成这项工作。

回答by Leif Carlsen

As indicated in other answers, System.getProperty provides the raw data. However, the Apache Commons Lang componentprovides a wrapper for java.lang.Systemwith handy properties like SystemUtils.IS_OS_WINDOWS, much like the aforementioned Swingx OS util.

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

回答by Vishal Chaudhari

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

回答by Nikesh Jauhari

A small example of what you're trying to achieve would probably be a classsimilar to what's underneath:

您试图实现的一个小例子可能class与下面的内容类似:

import java.util.Locale;

public class OperatingSystem
{
    private static String OS = System.getProperty("os.name", "unknown").toLowerCase(Locale.ROOT);

    public static boolean isWindows()
    {
        return OS.contains("win");
    }

    public static boolean isMac()
    {
        return OS.contains("mac");
    }

    public static boolean isUnix()
    {
        return OS.contains("nux");
    }
}

This particular implementation is quite reliable and should be universally applicable. Just copy and paste it into your classof choice.

这个特定的实现是非常可靠的,应该是普遍适用的。只需将其复制并粘贴到您class选择的位置即可。

回答by Wolfgang Fahl

some of the links in the answers above seem to be broken. I have added pointers to current source code in the code below and offer an approach for handling the check with an enum as an answer so that a switch statement can be used when evaluating the result:

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

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

The helper class is:

助手类是:

/**
 * 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 - the operating system detected
   */
  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 detectedOS;
  }
}

回答by TacB0sS

I liked Wolfgang's answer, just because I believe things like that should be consts...

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

so I've rephrased it a bit for myself, and thought to share it :)

所以我为自己改写了一下,并想分享它:)

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

回答by Kamidu

Try this,simple and easy

试试这个,简单易行

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