Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
588 views
in Technique[技术] by (71.8m points)

command line - How to compile java package structures using javac

I am trying to compile (from the command line) a java package that imports another package of my own. I was following a tutorial online but it seems that I get an error when I try to compile the final java file (CallPackage.java).

Here is the file structure:

+ test_directory (contains CallPackage.java)
   -> importpackage
       -> subpackage (contains HelloWorld.java)

Here is CallPackage.java:

/// CallPackage.java
import importpackage.subpackage.*;
class CallPackage{
  public static void main(String[] args){
  HelloWorld h2=new HelloWorld();
  h2.show();
  }
}

and here is HelloWorld.java:

///HelloWorld.java

package importpackage.subpackage;

public class HelloWorld {
  public void show(){
  System.out.println("This is the function of the class HelloWorld!!");
  }
}

Attempted Steps

  1. Go to the subpackage and compile HelloWorld.java with $javac HelloWorld.java.
  2. Go to test_directory and compile CallPackage.java with $javac CallPackage.java.

This gives me an error on the last command:

CallPackage.java:1: package importpackage.subpackage does not exist
import importpackage.subpackage.*;
^
CallPackage.java:4: cannot find symbol
symbol  : class HelloWorld
location: class CallPackage
  HelloWorld h2=new HelloWorld();
  ^
CallPackage.java:4: cannot find symbol
symbol  : class HelloWorld
location: class CallPackage
  HelloWorld h2=new HelloWorld();
                    ^
3 errors

How can I compile both packages? Thanks so much for any help!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The issue was that the class path needs to be set for each command (javac and java):

Attempted Steps

  1. instead of going to subpackage, compile HelloWorld.java from the top_level:

    $javac -cp . importpackage/subpackage/HelloWorld.java

  2. compile CallPackage.java in the same way:

    $javac -cp . CallPackage.java

  3. run the file using the class path also:

    $java -cp . CallPackage

NOTE: running "$java CallPackage" will give an error "Error: Could not find or load main class CallPackage"

In summary, during each step, the class path must be specified. It worked after running it as such.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...