如何使用Java确定计算机正在运行的OS?

java.lang包的System类提供了一个名为getProperty()的方法,该方法接受以下字符串参数之一,并返回相应的属性。

  • java.class.path-如果将此值作为参数传递,则该getProperty()方法返回当前的classpath

  • java.home-如果您将此值作为参数传递,则该getProperty()方法将返回JRE的当前Installation目录。

  • java.vendor-如果您将此值作为参数传递,则该getProperty()方法将返回JRE的当前供应商名称。

  • java.vendor.url-如果您将此值作为参数传递,则该getProperty()方法返回JRE的当前供应商URL。

  • java.version-如果将此值作为参数传递,则该getProperty()方法返回JRE的当前版本号。

  • line.separator-如果将此值作为参数传递,则该getProperty()方法将返回当前操作系统用于分隔文本文件中各行的值/序列。

  • file.separator-如果将此值作为参数传递,则该getProperty()方法返回用于分隔文件路径(/或\)中的目录的字符。

  • path.separator-如果您将此值作为参数传递,则该getProperty()方法将返回classpath环境变量的路径分隔符。

  • user.dir-如果您将此值作为参数传递,则该getProperty()方法将返回用户的工作目录。

  • user.home-如果您将此值作为参数传递,则该getProperty()方法将返回用户的主目录。

  • user.name-如果您将此值作为参数传递,则该getProperty()方法将返回用户的帐户名。

  • os.arch-如果您将此值作为参数传递,则该getProperty()方法将返回当前操作系统的体系结构。

  • os.name-如果您将此值作为参数传递,则该getProperty()方法将返回当前操作系统的名称。

  • os.version-如果您将此值作为参数传递,则该getProperty()方法将返回当前操作系统的版本。

要获取当前操作系统的名称,请getProperty()通过将值“ os.name”传递给该方法来调用该方法,如以下示例代码所示。

示例

public class Sample {
   public static void main(String args[]) {
      String os = System.getProperty("os.name");
      System.out.println("Current Os is: "+os);    
   }  
}

输出结果

Current Os is: Windows 10