running a batch file through java program

大城市里の小女人 提交于 2020-01-16 01:28:13

问题


I want to run a batch file through java program. The batch file itself runs a exe file with some filename as arguments. I tried this by creating a C program and running that exe through java. Is there any other way to run a batch file which itself runs a exe through java. Thanks in advance...


回答1:


public class CallingBatch {
public static void main(String[] args) {
Runtime run = Runtime.getRuntime();
try {
run.exec("cmd start /c C:/batfile.bat");
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("FINISHED");
}
}

Hope this will help you.




回答2:


You could use Runtime.exec and pass it cmd /c /path/to/your/batch/script.

As of Java 1.5, you can also use ProcessBuilder.

 Process p = new ProcessBuilder("cmd", "/c", "/path/to/batch/file").start();

The API docs for ProcessBuilder details a more complex setup with working directories and such.




回答3:


To start with playing with the batch file you have to take some time to learn PROCESSBUILDER and Runtime classes.

Program:

class RunBatch
{
    public static void main(String[] arg){

        Runtime runtime = null;
        try{
            runtime.getRuntime.exec("CMD START /C D:/myBatchFile.bat");   
        }
        catch(RuntimeException e){ 
            e.printStackTrace();
        }
    }
}



回答4:


My preferred method of starting any process from within java is to use ProcessBuilder



来源:https://stackoverflow.com/questions/4141645/running-a-batch-file-through-java-program

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!