Click to See Complete Forum and Search --> : Problem with package


Sayan Mukherjee
June 6th, 2003, 07:00 AM
Hi,

I have two .java files for my application: Caller.java and
Called.java . My working folder is d:/temp where Caller.java
is located. The file Called.java is located in d:/temp/pack1.

The two surce code files are attached.

When I try to compile Caller.java from d:/temp it works fine
and the .class files get created at the respective locations.

Now I archive the Called.class in a jar file called pack1.jar
and keep it in my working folder d:/temp where Caller.java
is also there.
(Note: The file Caller.class should remain outside any .jar file.)

The problem:
When I try to compile Caller.java with the pack1.jar available
in the same folder, I get the following error message:


D:/temp>javac Caller.java
Caller.java:1: package pack1 does not exist
import pack1.Called;
^
Caller.java:12: cannot access Called
bad class file: d:/temp/pack1.jar(Called.class)
class file contains wrong class: pack1.Called
Please remove or make sure it appears in the correct subdirectory of the classpath.
Called obj = new Called();
^
2 errors



D:/temp>javac -classpath .;d:/temp/pack1.jar Caller.java
Caller.java:1: package pack1 does not exist
import pack1.Called;
^
Caller.java:12: cannot access Called
bad class file: d:/temp/pack1.jar(Called.class)
class file contains wrong class: pack1.Called
Please remove or make sure it appears in the correct subdirectory of the classpath.
Called obj = new Called();
^
2 errors



My questions:
What is wrong with the compilation or the code?
How do I fix it?

P.S.: Kindly interpret the forward slash (/) in the compiler output
as the usual DOS or Windows back slash (\).

dlorde
June 6th, 2003, 10:42 AM
I downloaded your classes, put Called.java in a 'pack1' subdirectory, and compiled them - no problem. Then I jar'd Called.class in 'pack1.jar' in the same directory as Caller.java and compiled it with the command line:

javac -classpath .;d:/temp/pack1.jar Caller.java

It compiled with no errors.

The most likely cause of your problem is that the jar contains Called.class but not the correct path ('pack1'). Classes in a jar file must have a path that corresponds to their package. When you jar your Called.class, make sure the correct path is included. For example:

d:/temp>jar cvf pack1.jar pack1

This creates pack1.jar by jar'ing the directory pack1 (and all files & subdirectories in it). If you then look at the contents of pack1.jar, you will see the file(s) is stored together with its path, so the jar file is like a directory itself.

Jars are just directory hierarchies compressed into a single file...