TechBeamersTechBeamers
  • Learn ProgrammingLearn Programming
    • Python Programming
      • Python Basic
      • Python OOP
      • Python Pandas
      • Python PIP
      • Python Advanced
      • Python Selenium
    • Python Examples
    • Selenium Tutorials
      • Selenium with Java
      • Selenium with Python
    • Software Testing Tutorials
    • Java Programming
      • Java Basic
      • Java Flow Control
      • Java OOP
    • C Programming
    • Linux Commands
    • MySQL Commands
    • Agile in Software
    • AngularJS Guides
    • Android Tutorials
  • Interview PrepInterview Prep
    • SQL Interview Questions
    • Testing Interview Q&A
    • Python Interview Q&A
    • Selenium Interview Q&A
    • C Sharp Interview Q&A
    • PHP Interview Questions
    • Java Interview Questions
    • Web Development Q&A
  • Self AssessmentSelf Assessment
    • Python Test
    • Java Online Test
    • Selenium Quiz
    • Testing Quiz
    • HTML CSS Quiz
    • Shell Script Test
    • C/C++ Coding Test
Search
  • Python Multiline String
  • Python Multiline Comment
  • Python Iterate String
  • Python Dictionary
  • Python Lists
  • Python List Contains
  • Page Object Model
  • TestNG Annotations
  • Python Function Quiz
  • Python String Quiz
  • Python OOP Test
  • Java Spring Test
  • Java Collection Quiz
  • JavaScript Skill Test
  • Selenium Skill Test
  • Selenium Python Quiz
  • Shell Scripting Test
  • Latest Python Q&A
  • CSharp Coding Q&A
  • SQL Query Question
  • Top Selenium Q&A
  • Top QA Questions
  • Latest Testing Q&A
  • REST API Questions
  • Linux Interview Q&A
  • Shell Script Questions
© 2024 TechBeamers. All Rights Reserved.
Reading: Java ProcessBuilder to Launch a .bat file
Font ResizerAa
TechBeamersTechBeamers
Font ResizerAa
  • Python
  • SQL
  • C
  • Java
  • Testing
  • Selenium
  • Agile Concepts Simplified
  • Linux
  • MySQL
  • Python Quizzes
  • Java Quiz
  • Testing Quiz
  • Shell Script Quiz
  • WebDev Interview
  • Python Basic
  • Python Examples
  • Python Advanced
  • Python OOP
  • Python Selenium
  • General Tech
Search
  • Programming Tutorials
    • Python Tutorial
    • Python Examples
    • Java Tutorial
    • C Tutorial
    • MySQL Tutorial
    • Selenium Tutorial
    • Testing Tutorial
  • Top Interview Q&A
    • SQL Interview
    • Web Dev Interview
  • Best Coding Quiz
    • Python Quizzes
    • Java Quiz
    • Testing Quiz
    • ShellScript Quiz
Follow US
© 2024 TechBeamers. All Rights Reserved.
Java BasicJava Tutorials

Java ProcessBuilder to Launch a .bat file

Last updated: Mar 12, 2024 8:06 pm
By Meenakshi Agarwal
Share
6 Min Read
Java ProcessBuilder example to Launch a bat file
Java ProcessBuilder Example
SHARE

In this Java tutorial, we thought to come up with an example code to demonstrate batch file execution using the Java ProcessBuilder class.

Contents
Run the Java program from the command lineJava ProcessBuilder Code Snippet

It is our attempt to make you familiar with the concept of Java ProcessBuilder so that you can use it during the software development of your projects.

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 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 a Jar file. The jar is a universal format supported on almost all platforms. You can run it from the command line as well.

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

The Java code snippet embedded 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 the output reader thread.
  • We’ve successfully tested the code on the 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 the command line

There are 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.

java -cp your-classpath-dependencies-here -jar hello.jar "arg1" "arg2"

Ref: https://stackoverflow.com/questions/6777124/how-to-execute-jar-with-command-line-arguments

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());
    }
}

Summary – Java ProcessBuilder Example

Before concluding this tutorial, we just want to pass special thanks to our readers. We hope that this tutorial will 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

You Might Also Like

A Simple Guide to Exception Handling in Java

Difference Between Spring and Spring Boot

How to Use Java String Format with Examples

Java IRC Bot with Sample Code

Generate Random Number in Java – 10 Ways

Meenakshi Agarwal Avatar
By Meenakshi Agarwal
Follow:
Hi, I'm Meenakshi Agarwal. I have a Bachelor's degree in Computer Science and a Master's degree in Computer Applications. After spending over a decade in large MNCs, I gained extensive experience in programming, coding, software development, testing, and automation. Now, I share my knowledge through tutorials, quizzes, and interview questions on Python, Java, Selenium, SQL, and C# on my blog, TechBeamers.com.
Previous Article Ultimate python coding tips for testers and programmers. Ten Essential Python Coding Tips for Beginners
Next Article LoadRunner Interview Questions with Answers for Experienced QA 25 LoadRunner Interview Questions and Answers

Popular Tutorials

SQL Interview Questions List
50 SQL Practice Questions for Good Results in Interview
SQL Interview Nov 01, 2016
Demo Websites You Need to Practice Selenium
7 Sites to Practice Selenium for Free in 2024
Selenium Tutorial Feb 08, 2016
SQL Exercises with Sample Table and Demo Data
SQL Exercises – Complex Queries
SQL Interview May 10, 2020
Java Coding Questions for Software Testers
15 Java Coding Questions for Testers
Selenium Tutorial Jun 17, 2016
30 Quick Python Programming Questions On List, Tuple & Dictionary
30 Python Programming Questions On List, Tuple, and Dictionary
Python Basic Python Tutorials Oct 07, 2016
//
Our tutorials are written by real people who’ve put in the time to research and test thoroughly. Whether you’re a beginner or a pro, our tutorials will guide you through everything you need to learn a programming language.

Top Coding Tips

  • PYTHON TIPS
  • PANDAS TIPSNew
  • DATA ANALYSIS TIPS
  • SELENIUM TIPS
  • C CODING TIPS
  • GDB DEBUG TIPS
  • SQL TIPS & TRICKS

Top Tutorials

  • PYTHON TUTORIAL FOR BEGINNERS
  • SELENIUM WEBDRIVER TUTORIAL
  • SELENIUM PYTHON TUTORIAL
  • SELENIUM DEMO WEBSITESHot
  • TESTNG TUTORIALS FOR BEGINNERS
  • PYTHON MULTITHREADING TUTORIAL
  • JAVA MULTITHREADING TUTORIAL

Sign Up for Our Newsletter

Subscribe to our newsletter to get our newest articles instantly!

Loading
TechBeamersTechBeamers
Follow US
© 2024 TechBeamers. All Rights Reserved.
  • About
  • Contact
  • Disclaimer
  • Privacy Policy
  • Terms of Use
TechBeamers Newsletter - Subscribe for Latest Updates
Join Us!

Subscribe to our newsletter and never miss the latest tech tutorials, quizzes, and tips.

Loading
Zero spam, Unsubscribe at any time.
x