czArek czArek - 3 months ago 9
Java Question

Compile project and include libraries using batch script

In

CMD
I compile project with including libraries

java -cp app.jar;libs/*;. com.app.Main


and it works, but I want create
BATCH
script, which do exactly the same. I create
test.bat
and put code like below:

@ECHO off

java -cp app.jar;libs/*;. com.app.Main

PAUSE


But when I run the
test.bat
the
CMD
was shown and there is information
"Error: Could not find or load main class com.app.Main".


BATCH
script is located at the same folder as
app.jar
and
libs
folder.

What is wrong with this batch script?

Jay Jay
Answer

After Java 6, Classpaths could be built by using wildcard characters.

You can create a directory named classpath and put your JARs inside it. Then you can create your .bat file like this:

@ECHO off
java -cp .;classpath/* com.app.Main
pause

You should have a structure like this:

com
`---app
    `---Main.java
classpath
`---your-crital-code-1.0.jar
compile.bat

I see that a lot of people are asking this question on StackOverflow, so here is a little tip for you guys.

I usually avoid using the cd command, as it may create some hassle. In windows, you can Shift + Right Click to open a command window in a particular directory.

I always prefer relative paths over absolutes, so that I don't get into hassle of managing long paths.

Here is a little program that deals with this kind of problem. You can always refer to and contribute to it so that we can make good examples for Java beginners :)