从Java运行.bat / .cmd文件

我想从Java运行.cmd文件。 我有一些适合我的东西。 有人可以帮我理解我的程序可能出现的故障。

import java.io.IOException; /* How to run a batch .bat or .cmd file from Java? 1. I don't want the command window to open up. It should be in background. 2. Gracefully destroy any new process created. 3. Need to confirm the quality of the program with experts. */ public class RunBat { public static void main(String args[]) { Runtime run = Runtime.getRuntime(); //The best possible I found is to construct a command which you want to execute //as a string and use that in exec. If the batch file takes command line arguments //the command can be constructed a array of strings and pass the array as input to //the exec method. The command can also be passed externally as input to the method. Process p = null; String cmd = "D:\\Database\\TableToCSV.cmd"; try { p = run.exec(cmd); p.getErrorStream(); System.out.println("RUN.COMPLETED.SUCCESSFULLY"); } catch (IOException e) { e.printStackTrace(); System.out.println("ERROR.RUNNING.CMD"); p.destroy(); } } } 

我的解决方案可靠吗? 我怎样才能确保一旦执行.cmd就没有进程挂起。

谢谢。

我不知道你在用p.getErrorStream()做什么,你没有访问它。

确定结果的方法即执行的命令的退出代码是通过添加以下行

 p = run.exec(cmd); p.waitFor(); System.out.println(p.exitValue()); 

并将p.destroy()放入finally块中。

希望这可以帮助。

执行以下命令:

 cmd.exe /C d:\database\tabletoCSV.cmd 

cmd.exe /? 欲获得更多信息:

 > cmd /? Starts a new instance of the Windows command interpreter CMD [/A | /U] [/Q] [/D] [/E:ON | /E:OFF] [/F:ON | /F:OFF] [/V:ON | /V:OFF] [[/S] [/C | /K] string] /C Carries out the command specified by string and then terminates /K Carries out the command specified by string but remains [...] 

就像卡尔刚提到的那样

  • 您没有捕获任何输出错误/成功输出。
  • 您没有让进程线程等待exitValue。
  • 你看过ProcessBuilder课了吗?

无论如何,您可以查看以下代码

  Process proc = null; Runtime rt = Runtime.getRuntime(); try { proc = rt.exec(cmd); InputStream outCmdStream = proc.getInputStream(); InputStreamReader outCmdReader = new InputStreamReader(outCmdStream); BufferedReader outCmdBufReader = new BufferedReader(outCmdReader); String outLine; while ((outLine = outCmdBufReader.readLine()) != null) { System.out.println(outLine); } InputStream errStream = proc.getErrorStream(); InputStreamReader errReader = new InputStreamReader(errStream); BufferedReader errBufReader = new BufferedReader(errReader); String errLine; while ((errLine = errBufReader.readLine()) != null) { System.out.println(errLine); } int exitVal = proc.waitFor(); System.out.println("Process exitValue: " + exitVal); } catch (IOException e) { e.printStackTrace(); System.out.println("ERROR.RUNNING.CMD"); proc.destroy(); } } 

希望这可以帮助

这个代码的另一个问题是其他答案没有指出:如果你开始的进程生成(控制台)输出并且你没有连接它的输出流,它将停止并且没有明显的原因失败。 对于某些程序和环境,我发现有必要连接单独的线程以保持输出和错误流的消耗。 并捕捉他们的输出,这样你就不会失明。

如果您有一个现代Java(1.5版),您也可以将ProcessBuilder类视为启动外部程序的一种方法。