0

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

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

有任何想法吗?

4

4 回答 4

2

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

代替

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

while ((line = output.readLine()) != null) {
于 2012-08-03T14:26:21.363 回答
1

试试这样:

String line = output.readLine();

while (line != null) {
    System.out.println(line);
    line = output.readLine();
}
于 2012-08-03T14:27:05.733 回答
1
while ((output.readLine()) != null) {
    System.out.println(line);
}

应该

while ((line = output.readLine()) != null) {
    System.out.println(line);
}
于 2012-08-03T14:30:47.977 回答
0
String line = null;
while ((output.readLine()) != null) {
        System.out.println(line);
    }

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

while((line = output.readLine()) != null)
于 2012-08-03T14:28:30.800 回答