2012-08-03 35 views
0

好的,所以我一直在试验ProcessRuntime类,并且遇到了问题。当我尝试执行此命令时:cmd /c dir,输出为空。这里是我的代码片段:用Java执行命令行程序时只收到null

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 

任何想法?

回答

2

您从未设置您用于写入控制台的变量line

更换

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

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

哦,谢谢。我甚至没有意识到XD – mattbdean 2012-08-03 14:54:35

1

尝试这样的:

String line = output.readLine(); 

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

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

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

然后你知道它一定是对的。 – nook 2012-08-03 15:35:16

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

应该

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