2012-08-03 40 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); 
}