【问题标题】:Get Java Version using `Runtime.getRuntime().exec(commands)`使用 `Runtime.getRuntime().exec(commands)` 获取 Java 版本
【发布时间】:2018-04-16 02:50:33
【问题描述】:

我找到了,我们可以使用System.getProperty("java.version") 找到Java 版本。 从这里 - Getting Java version at runtime

但我已经使用Runtime.getRuntime().exec(commands) 完成了这样的编码 -

String[] commands ={"java", "-version"};
    String line;
    String cmdOutput = "";
    try {
        Process process = Runtime.getRuntime().exec(commands);
        process.waitFor();
        BufferedReader input = new BufferedReader(new InputStreamReader(process.getInputStream()));
        while ((line = input.readLine()) != null) {
            cmdOutput += (line + "\n");
        }
        System.out.println("output "+cmdOutput);
        input.close();
        }
    catch (Exception ex) {
        ex.printStackTrace();
    }

但是得到空白输出。

当我从命令提示符运行java -version 时,我们得到版本,我觉得它也应该返回相同的输出。

在我丢弃它并使用System.getProperty("java.version")之前,我能知道我在这里缺少什么吗?

提前致谢。

【问题讨论】:

  • 你检查过错误流吗?
  • @Andrew Stubbs:感谢它使用错误流工作。但是为什么它会进入错误流?
  • 不要使用Runtime.exec 来获取java 版本,除非您打算永远不将应用程序提供给其他任何人或在不同的机器上运行它。首先,JRE 可能在也可能不在PATH 系统变量中。其次,即使是这样,也不能保证您的应用程序将使用与 PATH 中存在的 JRE 相同的 JRE 运行
  • @blgt:知道了,谢谢。

标签: java cmd


【解决方案1】:

您没有在代码中获得版本,因为: java版本 打印到错误流,而不是标准输出,我不知道为什么。

你可以用:

java -version > output.txt

并看到它仍然打印到您的控制台,并且 output.txt 中没有任何内容。

或与:

java -version 2> error.txt

并看到没有打印任何内容,并且版本信息在error.txt中

这里问了为什么会这样的问题:Why does 'java -version' go to stderr?

【讨论】:

【解决方案2】:
public static String getJavaVersion()
  {
    String method = "getJavaVersion";
    String javaVersion = "";
    try
    {
      // Command:  wmic datafile where name="C:\\Windows\\System32\\msiexec.exe" get Version /value
      Process process = Runtime.getRuntime().exec("java -version");
      BufferedReader reader = new BufferedReader(new InputStreamReader(process.getErrorStream()));
      javaVersion = reader.readLine();

      System.out.println("Method: "+method+" -   "+javaVersion);
      while(javaVersion!= null)
      {
        if(javaVersion.trim().startsWith("Version"))
        {
          System.out.println("Method: "+method+" -   "+javaVersion);
          return javaVersion;
        }

        javaVersion=reader.readLine();
      }// end while
    }
    catch (IOException e)
    {
      System.out.println("Method: "+method+"  Could not check version "+e);
      e.printStackTrace();
      return "";
    }
    return javaVersion;
  }

【讨论】:

  • 虽然此代码 sn-p 可能是解决方案,但 including an explanation 确实有助于提高您的帖子质量。请记住,您是在为将来的读者回答问题,而这些人可能不知道您提出代码建议的原因。
猜你喜欢
  • 2012-06-21
  • 1970-01-01
  • 2015-12-09
  • 2011-04-28
  • 2013-01-21
  • 1970-01-01
  • 2012-10-14
  • 2011-02-22
相关资源
最近更新 更多