2014-01-31 19 views
0

我把一些C#代碼到Java使用過程中的java

System.Diagnostics.ProcessStartInfo procStartInfo = new System.Diagnostics.ProcessStartInfo("cmd", "/c " + command); 
// The following commands are needed to redirect the standard output. 
// This means that it will be redirected to the Process.StandardOutput StreamReader. 
procStartInfo.RedirectStandardOutput = true; 
procStartInfo.UseShellExecute = false; 
// Do not create the black window. 
procStartInfo.CreateNoWindow = true; 
// Now we create a process, assign its ProcessStartInfo and start it 
System.Diagnostics.Process proc = new System.Diagnostics.Process(); 
proc.StartInfo = procStartInfo; 
proc.Start(); 
// Get the output into a string 
string result = proc.StandardOutput.ReadToEnd(); 
// Display the command output. 

這是我嘗試將其轉換爲Java代碼。

我不知道如何運行一個命令並在java中使用進程。我GOOGLE了它,我發現類似的東西:

Process process = Runtime.getRuntime().exec(command); 
Integer result = process.exitValue(); 

在行

process.exitValue() 

它給了我java.lang.IllegalThreadStateException: process has not exited

回答

2

exec之後您需要等待命令完成process.waitFor()

0

process.exitValue()System.exit(number)獲取數 由於進程尚未退出,因此引發錯誤。 從C#代碼它看起來像你想獲得命令的輸出,這可以通過以下方式完成:

int i=0; 
String result = new String(); 
while((i = process.getInputStream().read()) >= 0) 
    result += (char)i; 
System.out.println(result);