简体   繁体   English

使用Java执行命令行程序时仅接收到null

[英]Only null recieved when executing a command line program with Java

Okay, so I have been experimenting with the Process and Runtime classes and I have run into a problem. 好的,所以我一直在尝试使用ProcessRuntime类,但是遇到了问题。 When I try to execute this command : cmd /c dir , the output is null. 当我尝试执行以下命令: cmd /c dir ,输出为null。 Here is a snippet of my code: 这是我的代码片段:

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();
}

And I get this for an output: 我得到这个作为输出:

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

Any ideas? 有任何想法吗?

You never set your line variable that you are using to write to the console. 您永远不会设置用于写入控制台的line变量。

Replace 更换

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

with

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

try it like this: 尝试这样:

String line = output.readLine();

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

should be 应该

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

Here is your problem. 这是你的问题。 You never set line to anything in your loop. 您永远不会在循环中设置任何行。 It remains null. 它保持为空。 You need to set line to value of output.readLine(). 您需要将line设置为output.readLine()的值。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM