Home > Blockchain >  How can I import file from outside of package?
How can I import file from outside of package?

Time:03-06

How can I import file from outside of package? example:

// this is a.java
package user.code.gui;
void method_a(){
    // do something
}

and

// this is b.java
package user.code;
void method_b(){
    // do something
}

and

// this is c.java
package user.extensions;
void method_c(){
    // do something
}

If I use "import c" in file a.java, it can't find this file because it's in a different package. The problem is, how can I import file c.java in file a.java?

CodePudding user response:

You need the other package to be there during compilation, and also during runtime; these are different things, but they both have the concept of a classpath.

Java always looks for things by translating type names to dir names; package a.b; class Foo {} is looked for in /a/b/Foo.class.

It scans each entry in the classpath for that. Classpath entries can be either directories, or jar files.

Build systems (maven, gradle, etc) and IDEs (eclipse, intellij, etc) - make this easily configurable and in general take care of it for you. You should use these tools; 99% of all java projects are compiled by IDEs and/or build tools.

Once you start having multiple packages, javac becomes unwieldy.

But, if you must use the command line for it:

Your directory structure:

/Users/Cflowe/workspace/MyAwesomeProject/src/user/code/gui/GuiClass.java
/Users/Cflowe/workspace/MyAwesomeProject/src/user/code/Whatever.java

and so on. To compile:

cd /Users/Cflowe/workspace/MyAwesomeProject
mkdir bin
javac -sourcepath src -d bin src/user/code/Whatever.java src/user/code/gui/GuiClass.java andSpecifyEveryOtherFileByHandHere

java -cp bin com.foo.Main
  • Related