1

Forgive my confusion with Java imports -- I come from a Python background.

I have some code that makes use of the itext library:

public static void makeADoc (Person p, String outfile) throws DocumentException,FileNotFoundException{
        Document document = new Document;
        PdfWriter.getInstance(document, new FileOutputStream(outfile));
        document.open();
        document.add(new Paragraph("Hello " + p.getFirst() + ",\n" + "You've just won the lotto!"));
        document.close();
    }

I have added the applicable itext-pdf jar files to the project's path. I have imported the entire library at the beginning of this class with a wildcard import statement:

import com.itextpdf.*;

Yet Eclipse is still giving me red underlined errors for Document objects and DocumentException and FileNotFound Exception objects. I am given the option to import the Document class from itextpdf, but it seems like my wildcard statement should have covered that. What's going on?

user1427661
  • 11,158
  • 28
  • 90
  • 132
  • 1
    In Eclipse, press `Ctrl-o`, this will do **Organize Imports**, that will solve your headache. You only have to select the proper class name if there are name conflicts. – gaborsch Jan 24 '13 at 17:47

1 Answers1

6

The FileNotFoundException is not from the itextpdf package but from the package java.io. So you should also add this import statement. Keep also in mind that using such wildcards import statements is sometimes considered bad practice because it could clutter your namespace.

Additionally, with your wildcard statement, you importing all the classes that are in the package com.itextpdf. However, the class DocumentException is in the package com.itextpdf.text and not com.itextpdf, so you would also have to add this import statement. Note that in Java there is no concept of sub packages, even though humans sometimes use this analogy. So com.itextpdf.text is a completely different package than com.itextpdf.

RoflcoptrException
  • 51,941
  • 35
  • 152
  • 200
  • So am I better off importing the classes on a one-at-a-time basis? For instance, if I implement Document Exception and PdfWriter, I just go back to them, Command-1 them, and then import those classes from the itext library instead of trying to import a catchall library? – user1427661 Jan 24 '13 at 17:44
  • 1
    Generally, it is considered better practice to import each class as you need it, instead of using wildcards. But there is no rule without exception :) Take also a look at this question: http://stackoverflow.com/questions/147454/why-is-using-a-wild-card-with-a-java-import-statement-bad – RoflcoptrException Jan 24 '13 at 17:49