29

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,216
  • 2
  • 20
  • 28

4 Answers4

59

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,421,763
  • 867
  • 9,128
  • 9,194
  • 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
  • 1,446
  • 21
  • 31
duffymo
  • 305,152
  • 44
  • 369
  • 561
  • 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

The question seems dated. But there is no answer mentioning the feature of running source file directly without using javac first, applicable for JDK 11+.

On linux:

java -cp some-library.jar:some-other-library.jar AClassName.java

On windows:

java -cp "some-library.jar;some-other-library.jar" AClassName.java
Hossain Cyrus
  • 65
  • 2
  • 5
-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
  • 1,446
  • 21
  • 31
YODA
  • 309
  • 1
  • 3