How to execute batch (.bat) file from Java

Well as the title suggests, we will attempt to know how to execute bat file from Java. When you are a Java Developer, a lot is expected from you and you need to do all kind of jugglery with Java. Be it a very complex enterprise application cutting through all kind of integration technology or simple standalone program Java , developer has to try his hands at all places to achieve success.

I encountered a similar task and I had to try and integrate small web application with standalone legacy .bat files. “Yes” I was trying to execute .bat file from Java Web Application. In this article I will share the code which I have used. The flow was like, I click on a button and it will execute batch file. This approach was selected because both the applications were hosted on same server and the web application was used by only few well trained users.

Instead of using regular Runtime.getRuntime() I opted to use the Plexus Common Utilities. The pom entry for that you can refer here

And here is the complete program that execute bat file from Java

The plexus util has an option to provide the writer for bat program output and for error output. You can capture that in stream and do the processing. The utility also has an variant of method executeCommandLine which takes timeout as one of the parameter.

In above program you can see I am trying to run a batfile from given directory. I am simply preparing the complete path for bat file and providing to that plexus util method. Thats it, once you run it, the program will call desired bat file.

The above program calls a bat file “run-java-program.bat” and which in turn calls another Java program which generates sample file. After I run this, I can see a file is generated as shown below.execute bat file from Java

Please let me know if you see any issues in above example that tells you how execute bat file from Java.

 

Add a Comment

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