Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/373.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何以编程方式确定Java中的操作系统?_Java_Operating System - Fatal编程技术网

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

如何以编程方式确定Java中的操作系统?,java,operating-system,Java,Operating System,我希望确定Java程序以编程方式运行的主机的操作系统(例如:我希望能够根据我是在Windows还是Unix平台上加载不同的属性)。100%可靠的最安全方法是什么?您可以使用: System.getProperty("os.name") 另外,您可能会发现此代码非常有用: class ShowProperties { public static void main(String[] args) { System.getProperties().list(System.ou

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

您可以使用:

System.getProperty("os.name")
另外,您可能会发现此代码非常有用:

class ShowProperties {
    public static void main(String[] args) {
        System.getProperties().list(System.out);
    }
}
它所做的只是打印出Java实现提供的所有属性。它将让您了解通过属性可以了解到的有关Java环境的信息。:-)

2008年10月:

我建议将其缓存在静态变量中:

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
}
这样,每次您请求操作系统时,在应用程序的生命周期内不会多次获取属性


2016年2月:7年多之后:

Windows 10有一个bug(在原始答案出现时不存在)。

请参阅“”

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

您可以在这里看到处理JVM版本(Vm.java和VmVersion.java)的类似类:


我发现是的。

如其他答案所示,System.getProperty提供了原始数据。但是,提供了一个方便的属性,就像前面提到的Swingx OS util一样。

您试图实现的一个小示例可能是一个类似于下面的
类:

String osName = System.getProperty("os.name");
System.out.println("Operating system " + osName);
import java.util.Locale;
公共类操作系统
{
私有静态字符串OS=System.getProperty(“OS.name”,“unknown”).toLowerCase(Locale.ROOT);
公共静态布尔值isWindows()
{
返回OS.contains(“win”);
}
公共静态布尔isMac()
{
返回操作系统包含(“mac”);
}
公共静态布尔值isUnix()
{
返回操作系统包含(“nux”);
}
}

这种特殊的实现是非常可靠的,应该是普遍适用的。只需复制并粘贴到您选择的
类中。

上面答案中的一些链接似乎已断开。我在下面的代码中添加了指向当前源代码的指针,并提供了一种使用枚举作为答案来处理检查的方法,以便在评估结果时可以使用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 - 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;
  }
}

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

所以我为自己重新表述了一下,并想与大家分享:)

/**
*操作系统的类型
*
*请将下面的注释作为伪许可证保留
*
*helper类检查运行此Java VM的操作系统
* http://stackoverflow.com/questions/228477/how-do-i-programmatically-determine-operating-system-in-java
*比照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
*/
公共枚举OSType{
MacOS(“mac”、“达尔文”),
Windows(“win”),
Linux(“nux”),
其他(“通用”);
私有静态OSType检测到的OS;
私有最终字符串[]密钥;
私有OSType(字符串…键){
this.keys=keys;
}
专用布尔匹配(字符串osKey){
for(int i=0;i
试试这个,简单易行

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

此代码用于显示有关系统os类型、名称、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));
    }
}

下面的代码显示了您可以从系统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
\
TL;DR

要访问操作系统,请使用:
System.getProperty(“OS.name”)


但是为什么不创建一个实用程序类,使其可重用呢!而且打多个电话可能要快得多。干净,干净,更快

为此类实用程序函数创建一个Util类。然后为每种操作系统类型创建公共枚举

public class Util {     
        public enum OS {
            WINDOWS, LINUX, MAC, SOLARIS
        };// Operating systems.

    private static OS os = null;

    public static OS getOS() {
        if (os == null) {
            String operSys = System.getProperty("os.name").toLowerCase();
            if (operSys.contains("win")) {
                os = OS.WINDOWS;
            } else if (operSys.contains("nix") || operSys.contains("nux")
                    || operSys.contains("aix")) {
                os = OS.LINUX;
            } else if (operSys.contains("mac")) {
                os = OS.MAC;
            } else if (operSys.contains("sunos")) {
                os = OS.SOLARIS;
            }
        }
        return os;
    }
}
现在,您可以很容易地从任何类中调用类,如下所示(另外,由于我们将os变量声明为静态的,所以识别系统类型只需要花费一次时间,然后可以使用它直到应用程序停止。)


就这样

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

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

  • com.sun.javafx.PlatformUtil
  • com.sun.media.jfxmediimpl.HostUtils
  • com.sun.javafx.util.Utils
例如:

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

我认为以下内容可以在更少的行中提供更广泛的覆盖范围

import org.apache.commons.exec.OS;

if (OS.isFamilyWindows()){
                //load some property
            }
else if (OS.isFamilyUnix()){
                //load some other property
            }

这里有更多详细信息:

在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>

net.java.dev.jna
jna
5.2.0

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

只需使用
com.sun.javafx.util.Utils
,如下所示

if ( Utils.isWindows()){
     // LOGIC HERE
}
或使用

boolean isWindows = OSInfo.getOSType().equals(OSInfo.OSType.WINDOWS);
       if (isWindows){
         // YOUR LOGIC HERE
       }

如果您在安全敏感的环境中工作,请通读。

请不要信任通过
系统#getProperty(String)
子例程获得的属性!实际上,几乎所有属性,包括
os.arch
os.name
os.version
都不是只读的
if ( Utils.isWindows()){
     // LOGIC HERE
}
boolean isWindows = OSInfo.getOSType().equals(OSInfo.OSType.WINDOWS);
       if (isWindows){
         // YOUR LOGIC HERE
       }
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;
        }
    }
}