In this post, I will show you how to create batch file and execute it using Java.
Prerequisites
The following configurations are required in order to run the application
Eclipse
JDK 1.8
Now create a Java project called “java-core” in Eclipse.
Then create a package called “com.roytuts.batch” in the Java project.
Now create a class called “BatchFile” with the below source code

package com.roytuts.batch;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
public class BatchFile {
    @SuppressWarnings("resource")
    public static void main(String[] args) {
        try {
            //create new file called sample in "d" drive
            File file = new File("d:\\sample.bat");
            FileOutputStream fos = new FileOutputStream(file);
            //write some commands to the file
            DataOutputStream dos = new DataOutputStream(fos);
            dos.writeBytes("cd \\");
            dos.writeBytes("\n");
            dos.writeBytes("echo %path%");
            dos.writeBytes("\n");
            //execute the batch file
            Process p = Runtime.getRuntime()
                    .exec("cmd /c start d:\\sample.bat");
            //wait for termination
            p.waitFor();
        } catch (Exception ex) {
        }
    }
}

Now run the above class, you will see one command prompt opens with echoing all commands.
Thanks for reading.

Tags:

1 thought on “Create Batch file using Java

Leave a Reply

Your email address will not be published. Required fields are marked *