How to create a batch file to run a Java program?

1 comment
I demonstrated how to create an .exe using maven in my previous post. Another way of distributing a software is by a run time which includes a batch file.

What is a batch file? 
A batch file is a type of script file which contains a series of instructions to be executed in turn. These are used to automate frequently performed tasks.  

You can write a batch file to compile, to create the JAR file and run the program. But in this post I mostly focus on creating run time and I assume that you have the .jar file already with you. You can use a tool like Maven or Ant to build your .jar file.

The following image shows the folder structure of my run time.
Folder Structure of the runtime
Here Blog-1.0-SNAPSHOT.jar is the JAR file of my program. My program is the same one I used in the previous post. So the program requires jdom2 library. One thing you should notice is that if you are using maven to build the program and unless you use a maven plugin to add dependencies into your JAR file, it does not include the other used .jars. Therefore in creating the run time you have to add those libraries in to the /lib folder. Also if your program requires any config files you can place them in the /config folder. Like wise if you have any log files write the program so that log files are placed in the /log folder.

Then let's create the start.bat file. Actually what you have to do is very easy. Just place following lines in a text file and save it with the extension of .bat.


title=XML Reader
java -Xmx256m -DAlert=true -classpath .;Blog-1.0-SNAPSHOT.jar;.\lib\jdom-2.0.5.jar Envision


pause

As you can see I have given the name of the JAR file, libraries to be used in the program (if you have many libraries give them as a series separated by semi colon ) and at the end the name of the main class.

It's really easy to make a run time, isn't it?

Happy coding! 

1 comment :