Search code examples
javajarclasspathexecute

How to run a jar with external libs


First, I'm working in a linux environment. Second, I've got one jar file which contains all of my project's classes, including the main, in one directory. Third, I've got all of the project's external dependent jars in a sub-directory called lib.

The question is how do I run my program? I've tried:

java -classpath ".:/lib/*"  com.pom.ticketprocessing.main.TicketProcessing
java -classpath ".:/lib/*"  tp.com.pom.ticketprocessing.main.TicketProcessing
java -classpath ".:/lib/*"  tp.jar.com.pom.ticketprocessing.main.TicketProcessing
java -classpath ".:/lib/*"  TicketProcessing
java -classpath "tp.jar:/lib/*.jar"  TicketProcessing
java -classpath "./tp.jar:./lib/*.jar"  TicketProcessing

In each case I get the error: Error: Could not find or load main class TicketProcessing

So, how do I run this program? Thanks in advance.


Solution

  • 1) Since your own jar is not int the lib directory, you need both of them in classpath. That's why lines 1 - 4 are not correct. They are all missing tp.jar.

    2) To refer jars, classpath should either use names of the jars without any wildcards, or use directory following one asterisk. It means you can use .../lib/abc.jar:.../lib/def.jar, or .../lib/*, but following will be just ignored: .../lib/*.jar.

    3) Pay attention to using of /. When path element begins with /, it means path in the file system root, not in the current directory.

    4) Usage of . is important only when calling scripts or executable binaries in the current directory. But when you provide path as an argument to Java, it is not necessary.

    In your case you need following command:

    java -classpath "tp.jar:lib/*" com.pom.ticketprocessing.main.TicketProcessing
    

    Or if you like dots:

    java -classpath "./tp.jar:./lib/*" com.pom.ticketprocessing.main.TicketProcessing