0

How do I run a program in Java, with several referenced libraries, .jar files, from a command line? I have put all my .jars in /lib folder, which is in the root folder of my project, and added those .jars to the build path. So my project now looks something like this:

Project:

-->/src/Entry.java, ... (all them .java files)

-->/bin/Entry.class, ... (all them other .class files)

-->/lib/commons-codec-1.10./(all them .jars)*

Now when i try to run the program from the cmd: I locate myself within the /bin folder and execute java Entry, but I get NoClassDefFound exception

How should I run this?

Paulo Costa
  • 127
  • 1
  • 10
Whizzil
  • 1,264
  • 6
  • 22
  • 39

2 Answers2

1

you need to tell JVM where to look for classes while running the program. the parameter that we use to tell jvm that is known as classpath

there are different ways to achieve that

  1. Recomended Add the classpath location to the run command , alternatively pass the jar locations, assuming you have two jar files a.jar and b.jar under you lib folder, the command should be java -cp".;lib/a.jar;lib/b.jar" Entry
  2. Either put the jar files into a location that is already under classpath (Since current folder is always under classpath, easiest option would be to put the jar under current folder , but this is not a recomended way to achieve)
  3. Modify you classpath variable under environment properties to list the folder containing your jar , which is a trivial way for achieving this.
Akash Yadav
  • 2,411
  • 20
  • 32
  • 1
    1) Wow, does `-cp` work with commas? I though it should be colon on *nix, semicolon on Windows? 2) Yet another way is to add a manifest with the `Class-Path` and `Main-Class` properties - then `java -jar` will do the trick. – Sergei Tachenov May 04 '15 at 13:51
  • Thanks for highlighting , i mistakenly typed that apologies – Akash Yadav May 04 '15 at 13:54
  • 1
    Two suggestions to make the answer even better; reference executable jars, and reference the possibility to use wildcards. http://stackoverflow.com/questions/1237093/how-to-use-a-wildcard-in-the-classpath-to-add-multiple-jars – Gimby May 04 '15 at 15:00
  • if i type something like this: java -cp"lib/a.jar;lib/b.jar" Entry, then it can not find the Entry class! – Whizzil May 04 '15 at 16:04
  • try java -cp".lib/a.jar;lib/b.jar" Entry - a "." in the class path to include the current folder – Akash Yadav May 04 '15 at 16:07
1

Create one batch file (.bat) and keep the jars inside that. whenever you want to run then directly run that batch file. I guess its very simple and efficient.

Example: @echo off

SET PATH=%PATH%;E:\Java\jdk1.6.0_45\bin // JDK path

SET LIB=%cd%\lib

set CP="" set CP=%CP%;%LIB%\antlr-2.7.6

set CP=%CP%;%LIB%\commons-codec-1.8.jar

set CP=%CP%;%LIB%\opencsv-2.3.jar

javac -classpath %cp% *.java

java -classpath %CP% -Xms256m -Xmx1024m -Xss2m T2DPreProcessing

pause

I hope it will help you. Thanks.