2013-09-30 52 views
2

當通過java web應用程序執行批處理文件時,會出現如下所述的錯誤。任何人都可以幫助我在java中執行命令

我不知道爲什麼只有情況1按預期工作,在case2,3,4只有一部分批處理文件執行。任何人都可以向我解釋爲什麼?非常感謝。

使用Runtime.getruntime().exec(command)

case1. cmd /c start C:\mytest.bat 
case2. cmd /c start /b C:\mytest.bat 
case3. cmd /c C:\mytest.bat 
case4. C:\mytest.bat 

mytest.bat

echo line1 >>%~dp0test.txt 
echo line2 >>%~dp0test.txt 
echo line3 >>%~dp0test.txt 
echo line4 >>%~dp0test.txt 
echo line5 >>%~dp0test.txt 
echo line6 >>%~dp0test.txt 
echo line7 >>%~dp0test.txt 
echo line8 >>%~dp0test.txt 
echo line9 >>%~dp0test.txt 
echo line10 >>%~dp0test.txt 
echo line11 >>%~dp0test.txt 
echo line12 >>%~dp0test.txt 
echo line13 >>%~dp0test.txt 
echo line14 >>%~dp0test.txt 
echo line15 >>%~dp0test.txt 
echo line16 >>%~dp0test.txt 
echo line17 >>%~dp0test.txt 
echo line18 >>%~dp0test.txt 
echo line19 >>%~dp0test.txt 
echo line20 >>%~dp0test.txt 
exit 

結果執行命令的test.txt

情況1:

line1 
line2 
line3 
line4 
line5 
line6 
line7 
line8 
line9 
line10 
line11 
line12 
line13 
line14 
line15 
line16 
line17 
line18 
line19 
line20 

例2,3,4:

line1 
line2 
line3 
line4 
line5 

回答

1

也許這是因爲你的程序的底層程序(的mytext.bat執行)完成之前終止。在你的第一種情況下,你使用start,它在它自己的環境中開始執行,所以即使它的父節點終止,執行也會繼續。所有其他命令都會在當前環境中執行批處理文件,並在您的應用程序中終止。

要解決此問題,您必須等待mytext.bat的執行完成。有幾種方法可以做到這一點,但我會建議使用一個進程生成器:

ProcessBuilder b = new ProcessBuilder("cmd", "/c", "C:\\mytest.bat"); 
Process p = b.start(); 
p.waitFor(); 

要使用你的方法:

Process p = Runtime.getruntime().exec(command) 
p.waitFor(); 
+0

你應該注意到'p.waitFor()'可以拋出一個'InterruptedException'那麼應該如何處理。 –

-1

當你不使用/ B選項或打開窗口中執行命令沒有開始,你需要保持一個暫停。在這裏,我停下了一秒鐘,程序完美地工作。

public class MyTest{ 
    public static void main(String args[]) throws Exception{ 
     //Runtime.getRuntime().exec("cmd /c start D:\\mytest.bat");//No pause required 
     Runtime.getRuntime().exec("cmd /c start /b D:\\mytest.bat");//pause required 
     //Runtime.getRuntime().exec("cmd /c D:\\mytest.bat");//pause required 
     //Runtime.getRuntime().exec("D:\\mytest.bat");//pause required 
     Thread.sleep(1000);//Pause for one second 
    } 
} 
+0

如果有問題的命令在第二秒內終止,則暫停一秒鐘纔會起作用。任何比這更多的命令將遭受意外終止。 –

+0

確實如此,但基於OP的要求就足夠了。 'Process.waitFor()'也不起作用。 –

+0

'Process.waitFor()'應該已經工作了。爲什麼不呢? (你檢查了正確的終止?) –

0

只需添加/等待你的命令第二個命令是這樣開始:

cmd /c start C:\mytest.bat 
case2. cmd /c start /wait /b C:\mytest.bat 
case3. cmd /c /wait C:\mytest.bat 
case4. C:\mytest.bat 
相關問題