在Java中运行bat文件,并等待 [英] Run bat file in Java and wait

查看:1556
本文介绍了在Java中运行bat文件,并等待的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您会认为,从Java推出一个bat文件将是一件容易的事,但没有...我有一个bat文件,做从一个文本文件中读取值的环一些SQL命令。这或多或少是这样的:

You would think that launching a bat file from Java would be an easy task but no... I have a bat file that does some sql commands for a loop of values read from a text file. It is more or less like this:

FOR /F %%x in (%CD%\listOfThings.txt) do sqlcmd -Slocalhost\MSSQL %1 %2 -d %3 -i %CD%\SQLScripts\\%%x
exit

不要担心,他们并不重要的细节。我要的是简单地从内部的Java运行这个批处理文件,让它等到执行完毕。显然,这是不容易的。我到目前为止是这样的:

Don't worry about the specifics they are not important. What i want is to simply run this bat file from within Java and have it wait until execution is finished. Apparently it is not easy. What i have so far is this:

Runtime.getRuntime().exec("cmd /K start SQLScriptsToRun.bat"
                    +" -U"+getUser()
                    +" -P"+getPass()
                    +" " + projectName);
return true;

的问题是,在exec()方法立即返回。 BAT文件运行一个良好的2-3分钟。我试图消除开始,但无济于事。我尝试了许多变化,但它让我无处。如何做到这一点简单的任务任何想法?

The problem is that the exec() method returns immediately. The bat file runs for a good 2-3 minutes. I tried removing the start but to no avail. I tried many variations but it got me nowhere. Any ideas on how to do this simple task?

推荐答案

您不应该忽视的<一个返回值href=\"http://java.sun.com/javase/6/docs/api/java/lang/Runtime.html#exec%28java.lang.String%5b%5d%29\"><$c$c>.exec().它给你一个 过程 对象,您可以<$c$c>waitFor(),像这样的:

You should not ignore the return value of .exec(). It gives you a Process object that you can waitFor(), like this:

final Process process = Runtime.getRuntime().exec("blahblahblah");
final int exitVal = process.waitFor();
// if exitVal == 0, the command succeeded

这篇关于在Java中运行bat文件,并等待的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆