有人帮我在java中执行命令

时间:2013-09-30 07:08:34

标签: java windows cmd

通过java Web应用程序执行批处理文件时,如下所述有错误。

我不知道为什么只有案例1按预期工作,在案例2,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

3 个答案:

答案 0 :(得分:1)

可能发生这种情况是因为您的程序在底层进程(执行mytext.bat)之前终止。在第一种情况下,您使用start在其自己的环境中开始执行,因此即使其父级终止也会继续执行。所有其他命令在当前环境中执行批处理文件,并随应用程序终止。

要解决此问题,您必须等待mytext.bat的执行完成。有几种方法可以做到这一点,但我建议使用Process Builder:

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

使用您的方法:

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

答案 1 :(得分: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

答案 2 :(得分:-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
    }
}