June 25, 2013

Java: silly newbie issue about path used in import statement

Ggkmath’s Question:

I’m working through the example here:

http://www.vogella.com/articles/JavaPDF/article.html

In my file, I’ve got:

package com.mycompanyname.mydirectory;

import com.mycompanyname.OneOfMyClasses;
import com.itextpdf.text.Document;
...

 public class MyClass {
     ...
 }

Everything is working fine. What I don’t understand is that since I just copied the import statement directly from the link above for the iText portion — why does com.itextpdf.text.Document work?

I mean, if I look in directory com.mycompanyname I can see OneOfMyClasses.java there.

But in the com directly, there is no itextpdf directory (although maybe my user doesn’t have permission to see it(?)).

Hoping someone can help me understand what I’m missing here. Doesn’t the import point to a specific directory that I should be able to see the class? Is there a different com directory somewhere that iText is using, and com.itextpdf.text points to there? (if so, where’s the directory located)?

I installed the jar file for iText in the lib folder as per usual, and made sure it was included in the classpath.

Those classes are inside a JAR file that is added to the classpath:

Create a new Java project “de.vogella.itext.write” with the package “de.vogella.itext.write”. Create a folder “lib” and put the iText library (jar file) into this folder. Add the jar to your classpath.

import statements will look inside whatever directory trees are in the classpath, which includes the current directory at compilation time (tipically the src/ directory in your project) as well as any directory specified through environment variable or JVM startup parameter. See this about the classpath.

EDIT

You do need the imports whenever you use classes across packages. Every public class/interface you define is in a package. If whatever you are referencing belongs to another package, you need to import it.

JARs are zip files that contain directories and files inside. It’s the same as plain directories and files, only packed.

That class is most probably imported in a JAR library. Inside such JAR file, the class files are kept in exact package/folder structure as you use when importing them.

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!