Search code examples
javajavac

use javac and java to excute class file with extern classes under other directory


I try to use javac to compile my javafile javac Main.java -cp ./lib HelloWorld.java and I got this javac: file not found: HelloWorld.java here is my java sourcefile: Main.java under ./

    import lib.*;

    public class Main 
    {
        public static void main (String []args)
        {
            HelloWorld hw = new HelloWorld ();
            System.out.println (hw.getMsg ());
        }
    }

and HelloWorld.java under ./lib

package lib;

public class HelloWorld
{
    public String getMsg ()
    {
        return "HelloWorld!";
    }
}

Any help would be appreciated!


Solution

  • Your command should be

    javac Main.java lib/HelloWorld.java
    

    Your attempt fails for a couple of reasons:

    • the -cp lib (if required) should be before the sourcecode pathnames
    • the classpath is not used to find source files; it is for finding compiled files.

    In this case, setting the classpath to ./lib is wrong for another reason. The directory lib actually corresponds to the package name for the HelloWorld class. If the classpath was ./lib, then java and javac would look for the compiled version of HelloWorld.java in

       ./lib/lib/HelloWorld.class