简体   繁体   中英

Java Classpath not using current directory

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

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 java -cp . Main .

If that DOES work

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).

If that does not work

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 .

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?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM