从Java运行.bat/.cmd文件

dRv*_*dRv 5 java

我想从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();  
        }  
    }  
}  
Run Code Online (Sandbox Code Playgroud)

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

谢谢.

YoK*_*YoK 5

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

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

p = run.exec(cmd);
p.waitFor();
System.out.println(p.exitValue());
Run Code Online (Sandbox Code Playgroud)

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

希望这可以帮助.