Java ProcessBuilder example to Launch a bat file with arguments

Most of the test automation frameworks need to run a batch file or external programs. As they have to perform system related tasks such as date-time changes, copy files/folders and other file system related stuff. In this Java tutorial, we thought to come up with an example code to demonstrate batch file execution using Java ProcessBuilder class. It is our attempt to make you familiar with the concept of Java ProcessBuilder so that you can use it during software development of your projects.

In the next section, you can check out the Java code to run the batch file. This sample code can easily integrate with any test framework that uses Java. However, you can also create a new Java project where you can chip in the given code. Then you can build and export the project as Jar file. Jar is a universal format supported on almost all the platforms. You can run it from the command line as well.

Just for your information, if you are interested in learning about Java JNA concept. Please refer the following blog post on Java JNA concept.

The Java code snippet embed below furnishes the following features.

Java ProcessBuilder Example – Description.

  • This code snippet can also be used to run any executable program apart from the batch file.
  • It allows passing arguments to the target program separated by spaces.
  • The program waits for the execution of the batch file or the target program to complete.
  • Reads the execution output buffer in a background thread to avoid any hang scenario.
  • Displays the program output after completing the execution.
  • In this code, we have used the Java anonymous inner class to initiate output reader thread.
  • We’ve successfully tested the code on Windows platform, but it’ll work the same on Linux and Mac OS X as well.
Java ProcessBuilder example to Launch a bat file

Java ProcessBuilder Example

Run the Java program from command line.

There are following two ways to run a Java program from the console.

1) You can export your Java project as a Jar file. Then use the following command to run it.

2) If you just want to run a Java class from the command line, then use the below command to execute and pass arguments.

💡 java -cp <Class File Path> <Java Class Name> <arg1> <arg2> <arg3>

Java ProcessBuilder Code Snippet.

package com.techbeamers.processbuilderdemo;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

/**
 * Java ProcessBuilder Demo
 */
public class ProcessBuilderDemo {
	public static void main(String[] args) throws IOException {
		// This code demonstrate using Java ProcessBuilder class to run a batch
		// file
		// Java ProcessBuilder and BufferedReader classes are used to implement
		// this.
		System.out.println(" ");
		System.out.println("==========Arguments Passed From Command line===========");
		for (String s : args) {
			// Iterate through String array in Java (args list)
			System.out.println(s);
		}
		System.out.println("============================");
		System.out.println(" ");
		final StringBuffer sb = new StringBuffer();
		int processComplete = -1;
		ProcessBuilder pb = new ProcessBuilder(args);
		pb.redirectErrorStream(true);
		try {
			final Process process = pb.start();
			final InputStream is = process.getInputStream();
			// the background thread watches the output from the process
			new Thread(new Runnable() {
				public void run() {
					try {
						BufferedReader reader = new BufferedReader(
								new InputStreamReader(is));
						String line;
						while ((line = reader.readLine()) != null) {
							sb.append(line).append('\n');
						}
					} catch (IOException e) {
						System.out
								.println("Java ProcessBuilder: IOException occured.");
						e.printStackTrace();
					} finally {
						try {
							is.close();
						} catch (IOException e) {
							e.printStackTrace();
						}
					}
				}
			}).start();
			// Wait to get exit value
			// the outer thread waits for the process to finish
			processComplete = process.waitFor();
			System.out.println("Java ProcessBuilder result:" + processComplete);
		} catch (Exception e) {
			e.printStackTrace();
		}
		System.out.println("Java ProcessBuilder - return=: " + sb.toString());
	}
}

Java ProcessBuilder Example – Wrap Up

Before concluding this tutorial, we just want to pass special thanks to our readers. We wish that this tutorial would be quite useful for you. In case, you have another approach to run a batch file or external program with arguments. Please do share it with us.

And if you have liked this post, please share it with others or on any social media platforms you like. Your feedback is always welcome and precious for us to do better next time. So you are invited to place your thoughts in the comment section just below the post.

All the Best,

TechBeamers.

4 Comments

  1. Yailenis Reply
    • Harsh S. Reply
  2. James Gosling the Java geek Reply
    • Harsh S. Reply