开发者

running a batch file through java program

开发者 https://www.devze.com 2023-01-24 21:24 出处:网络
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

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 f开发者_开发知识库ile which itself runs a exe through java. Thanks in advance...


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.


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.


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


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

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号