【问题标题】:Only null recieved when executing a command line program with Java使用 Java 执行命令行程序时只收到空值
【发布时间】:2012-08-01 14:45:31
【问题描述】:

好的,所以我一直在尝试 ProcessRuntime 类,但遇到了问题。当我尝试执行此命令时:cmd /c dir,输出为空。这是我的代码的 sn-p:

try {
    Runtime runtime = Runtime.getRuntime();
    Process process = runtime.exec("cmd /c dir");

    BufferedReader output = new BufferedReader(new InputStreamReader(process.getInputStream()));

    //BufferedReader serverOutputError = new BufferedReader(new InputStreamReader(serverStart.getErrorStream()));

    String line = null;

    while ((output.readLine()) != null) {
        System.out.println(line);
    }

    int exitValue = process.waitFor();
    System.out.println("Command exited with exit value: " + exitValue);

    process.destroy();
    System.out.println("destroyed");
} catch (IOException e) {
    e.printStackTrace();
} catch (InterruptedException e) {
    e.printStackTrace();
}

我得到这个作为输出:

(18 lines of just "null")
Command exited with exit value: 0
destroyed

有什么想法吗?

【问题讨论】:

    标签: java command-line process runtime


    【解决方案1】:

    您永远不会设置用于写入控制台的 line 变量。

    替换

    while ((output.readLine()) != null) {
    

    while ((line = output.readLine()) != null) {
    

    【讨论】:

      【解决方案2】:

      像这样尝试:

      String line = output.readLine();
      
      while (line != null) {
          System.out.println(line);
          line = output.readLine();
      }
      

      【讨论】:

        【解决方案3】:
        while ((output.readLine()) != null) {
            System.out.println(line);
        }
        

        应该是

        while ((line = output.readLine()) != null) {
            System.out.println(line);
        }
        

        【讨论】:

          【解决方案4】:
          String line = null;
          while ((output.readLine()) != null) {
                  System.out.println(line);
              }
          

          这是你的问题。您永远不会在循环中将 line 设置为任何内容。它仍然为空。 您需要将 line 设置为 output.readLine() 的值。

          while((line = output.readLine()) != null)
          

          【讨论】:

            猜你喜欢
            • 2011-06-24
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2011-05-13
            • 1970-01-01
            相关资源
            最近更新 更多