Create Batch File Using Java

Batch File Creation

In this post, I will show you how to create batch file (having an extension as .bat) 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 give 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.

The method exec(String str) has been deprecated in Java 18 or so. So I am going to use exec(String[] commandarray) method to open the command prompt using Java code.

public static void main(String[] args) {
		try {
			final String fileName = "sample.bat";
			final String filePath = "C:/eclipse-workspace";
			
			// create new file called sample.bat
			File file = new File(filePath + File.separator + fileName);
			
			FileOutputStream fos = new FileOutputStream(file);

			// write some commands to the file
			DataOutputStream dos = new DataOutputStream(fos);
			dos.writeBytes("cd \\");
			dos.writeBytes("\n");
			dos.writeBytes("%path%");
			dos.writeBytes("\n");
			dos.close();

			// execute the batch file
			//Process p = Runtime.getRuntime().exec("cmd /c start sample.bat"); // The method exec(String) from the type
																				// Runtime is deprecated since version
																				// 18
			
			//Java 19 fix
			//String[] command = {"cmd.exe", "/c", "Start", filePath+File.separator+fileName};
            //Process p =  Runtime.getRuntime().exec(command);
            
			//Helps in debugging if any issue occurs
			ProcessBuilder pb = new ProcessBuilder("cmd", "/c", "start", fileName);
			pb.directory(new File(filePath));
			Process p = pb.start();
			
			// wait for termination
			p.waitFor();			
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}

An as alternative way you can also use ProcessBuilder instead of Process, the ProcessBuilder helps in debugging to check any issue occurred in the program.

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

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

Source Code

Download

1 thought on “Create Batch File Using Java

Leave a Reply

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