28

So, I can do this very well:

java mypackage.MyClass

if ./mypackage/MyClass.class exists. I can also happily do this:

java -cp myjar.jar mypackage.MyClass

if the class file exists in the appropriate part of the jar. Easy stuff. But I can't for the life of me manage to do something like this:

java -cp utilities.jar mypackage.MyClass

where ./mypackage/MyClass.class exists, and where ./utilities.jar exists (not containing MyClass, of course).

Am I about to feel stupid?

amara
  • 2,168
  • 2
  • 18
  • 28

3 Answers3

57

Possibly :)

# On Unix
java -cp utilities.jar:. mypackage.MyClass

# On Windows
java -cp utilities.jar;. mypackage.MyClass

Basically that's just including . (the current directory) on the classpath as well as the jar file.

Jon Skeet
  • 1,335,956
  • 823
  • 8,931
  • 9,049
  • Is `-cp` a short form for `-classpath`? – overexchange Dec 06 '17 at 12:03
  • @overexchange: Yes. (Running `java -?` would have told you that.) – Jon Skeet Dec 06 '17 at 12:03
  • this is not working for me.... ```java -cp argparse4j-0.9.0.jar:. Demo Error: Could not find or load main class Demo Caused by: java.lang.ClassNotFoundException: Demo``` – rica01 Sep 30 '21 at 21:55
  • @rica01: Well is `Demo.class` in the current directory? We can't really tell much just from that. (And what operating system are you using?) – Jon Skeet Oct 01 '21 at 05:41
  • it was. I honestly gave up on this, it was taking tooooooo much time for something that should be extrasimple. thanks anyways jon! – rica01 Oct 01 '21 at 09:04
7

Try this if you're on Windows:

java -cp .;utilities.jar mypackage.MyClass

Or this if you're on Linux:

java -cp .:utilities.jar mypackage.MyClass

The current directory is not in the CLASSPATH by default when you specify a value for -cp.

Cadoiz
  • 975
  • 12
  • 24
duffymo
  • 299,921
  • 44
  • 364
  • 552
  • No, the current directory *is* the classpath by default; it's only when you specify a *different* classpath that you get problems. – Jon Skeet Jun 20 '11 at 10:06
  • @Vuntic: That would certainly be accurate. Maybe @duffymo would like to edit to that wording :) – Jon Skeet Jun 20 '11 at 10:12
-1

You should include the mypackage.MyClass into the CLASSPATH or the -cp parameter. For example:

java -cp utilities.jar;myjar.jar mypackage.MyClass

The path separator is ; on windows and : on Unix/Linux

Cadoiz
  • 975
  • 12
  • 24
YODA
  • 309
  • 1
  • 3