Create Batch file using Java

In this post, I will show you how to create batch file and execute it using Java.


The following configurations are required in order to run the application

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;


public class BatchFile {

    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("echo %path%");

            //execute the batch file
            Process p = Runtime.getRuntime()
                    .exec("cmd /c start d:\\sample.bat");
            //wait for termination
        } catch (Exception ex) {



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

Thanks for reading.

Create Batch file using Java

0 thoughts on “Create Batch file using Java

Leave a Reply

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

Scroll to top