Create Batch file using Java

In this post, I will show you how to create batch file and execute it using Java. Along with this batch file I am also going to write some content in this batch file so that while executing this batch file I will get some output. Batch file is generally created under Windows operating system and it is used to perform various configurable tasks. The extension of the batch file is .bat.

Prerequisites

Java

Create and Execute Batch File

In this section I am going to create batch file with some content using Java and once it is created I am also going to execute it using the Java program.

package com.roytuts.java.batch.file;

import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;

public class BatchFile {

	public static void main(String[] args) {
		try {
			// create new file called sample in "d" drive
			File file = new File("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 sample.bat");

			// wait for termination
			p.waitFor();

			dos.close();
		} catch (Exception ex) {
		}
	}

}

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

The "echo %path%" command will display the environment variables in the command line tool.

Source Code

Download

Thanks for reading.

Related posts

One Thought to “Create Batch file using Java”

  1. mohan

    thank you its very helpfulll

Leave a Comment