Java command error: the main class cannot be found or cannot be loaded

The Java version I use is:

java version "1.8.0_191"

Code directory structure: Insert picture description here
ClassPathDemo.java:

package com.jiaobuchong;

import java.util.HashSet;
import java.util.Set;

import org.apache.commons.lang3.StringUtils;

public class ClassPathDemo {
    
    

    public static void main(String[] args) {
    
    
        Set<String> set = new HashSet<>();
        set.add("jack");
        System.out.println(set);
        System.out.println(jarTest("one"));
    }

    private static String jarTest(String a) {
    
    
        if (StringUtils.isBlank(a)) {
    
    
            return null;
        }
        return a.toUpperCase();
    }
}

Use javac command to compile:
Insert picture description here
the classpath is specified here, otherwise the compiler cannot find the StringUtils class.
In the test directory:
Insert picture description here
What the hell is this? Report it 找不到或无法加载主类. I multi-query data and no fruit, dependent jar package directory specified: ~/test/jar/commons-lang3-3.4.jar, compiled class files in the directory is also specified: ~/test.

After a test, turned out to be a problem with the specified directory:
Insert picture description here
When I ~/testreplaced the absolute path: /Users/jackchou/testnormal, original classpath specified directory, the second directory can not use ~the first directory can. In order to avoid errors, the classpath specifies an absolute path java -classpath /Users/jackchou/test/jar/commons-lang3-3.4.jar:/Users/jackchou/test com.jiaobuchong.ClassPathDemo, and this Java class can be run in any directory.
Insert picture description here
For the above command to run normally, you need to ensure that the java command is executed in the directory of the compiled class.

The default classpath is the current directory, when the custom classpath will default to overwrite, to join the current directory in the classpath, directly .on the line.

Reference: Setting the Class Path
understanding of classpath and how to use it
. Detailed explanation of CLASSPATH in JAVA projects.
JAVA and JAVAC command lines; java is compiled and run with package name, and run with external dependent jar package

Guess you like

Origin blog.csdn.net/jiaobuchong/article/details/89052616