java - 从 Java 运行 .bat/.cmd 文件

标签 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();  
        }  
    }  
}  

我的解决方案可靠吗?我如何才能确保在执行 .cmd 后没有进程挂起。

谢谢。

最佳答案

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

确定结果的方法,即执行命令的退出代码是在

之后添加以下行
p = run.exec(cmd);
p.waitFor();
System.out.println(p.exitValue());

并将 p.destroy() 放在 finally block 中。

希望这对您有所帮助。

关于java - 从 Java 运行 .bat/.cmd 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3275141/

相关文章:

Java非阻塞语句之间的执行延迟

java - 如何在 Java 上的选定项目列表微调器上设置值?

java - 声明后初始化数组

java - PHP 套接字发送数据,但 Java 套接字未接收数据

Java Thread() sleep 问题

java - 为什么 libGDX image.getHeight() 返回零?

java - 为什么我的匿名类操作监听器无法退出 Java GUI?

java - 哪种 Java API 数据结构适合 HTML 树?

java - 为什么不能将 new Base() 传递给 <?扩展基地>?

java - 从 2D 操纵杆获取 3D 旋转轴和角度