简体   繁体   中英

running a batch file through java program

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...

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.

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

我在java中启动任何进程的首选方法是使用ProcessBuilder

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM