Using Batch Files to Compile and Run Java Programs

If you have gone through our previous lessons on compiling and running programs from the command line, you should understand that it is useful to save these commands somewhere. This is where special batch (.bat) and shell (.sh) files come in. You can create files with the .bat or .sh extensions that contain multiple commands. Batch files are used for Windows, while shell scripts are used for Linux.
In this article, we will look at examples using batch (.bat) files. These files can be executed both from the command line and from Windows Explorer. Let's see how it works.
We have a project containing the src
and classes
folders. A run.bat
file is also added to the root directory:
Let's take a look at its content:
javac -d classes -cp src src/first/Example1.java
java -cp classes first.Example1
As you can see, this batch file contains two commands. The first command compiles the Example1.java
file, and the second command runs it.
Now let's run the batch file from the command line. Press Windows+R and type cmd
:
Navigate to the required directory. To run the batch file, simply type its name:
This executes the two commands specified in the file.
The second way to run a batch file is to simply double-click on it. In this case, the batch file runs, executes all commands, and the window immediately closes. To prevent the command window from closing right away and to see the results, add the pause
command at the end of the batch file:
javac -d classes -cp src src/first/Example1.java
java -cp classes first.Example1
pause
Now the command window will stay open after execution, displaying the message: "Press any key to continue." Once you press a key, the window will close.
With batch files, you can compile and run your programs from the command line more efficiently.

Please log in or register to have a possibility to add comment.