Reputation: 40
Yes... Again question about classpath. I compiled class file using command javac Main.java
, then i tried to execute it by java Main
And what do you think? I got that famous error: Error: Could not find or load main class Main
. Why? I set the classpath env var to ".;" (without " of course). Whats wrong? Im using jdk 1.8.0_51.
In IDE (im using intellij idea 2021.3) everything is ok.
The only imported class is java.io.File.
It only works if i run it using command java -cp <path to dir not including package folders> <full qualified class name>
Windows 8.1
Upvotes: 0
Views: 819
Reputation: 103773
Relying on the CLASSPATH
system variable is a bad idea. One machine can be used to run many varied apps, so the concept of a 'global setting' is silly.
Try java -cp . Main
.
Then you've been messing with your CLASSPATH
environment var and removed .
from it. Put it back. Or better yet forget about CLASSPATH; always use -cp
; use -cp .
if you like. Or make jar
files and run them with java -jar thejar.jar
, which ignores both CLASSPATH
and the -cp
parameter (instead that will look at the Class-Path
entry in the jar manifest).
Then you were not in the appropriate directory. Or, you're confused about packages. Let's say your Main.java
looks like this:
package com.foo;
public class Main {
public static void main(String[] args) {
System.out.println("Hello");
}
}
And you compile it; a Main.class
file shows up.
java
cannot run this unless Main.class
is in a directory named foo
, and that directory is in turn in a directory named com
. Then, you put the directory that contains com
on the classpath. Not the directory that contains Main.class
. And then you run java -cp theDirThatContainsCom com.foo.Main
. It is not possible to run this file with java -(does not matter what you try it cannot be done) Main
- because you provide the full name of the class you want to run to java
, and the full name is com.foo.Main
.
Upvotes: 1
Reputation: 741
Current directory (.
) is a default classpath. But it does not include subdirectories automatically. So if you have packages, the directories should be added to classpath explicitly.
See a bit more info here What's the default classpath when not specifying classpath?
Upvotes: 0