2013-09-30 38 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 
相关问题