Krt_Malta
Krt_Malta

Reputation: 9465

Importing libraries in Eclipse programmatically

Is there a way I could put a library (Jar file) into an Eclipse project programatically? Up to now I've managed to do an external reference to it programatically using

    IPath path = new Path("C:\\myfolder\\mylibrary.jar");
    libraries.add(JavaCore.newLibraryEntry(path, null, null));
    //add libs to project class path
    try {
        javaProject.setRawClasspath(libraries.toArray(new IClasspathEntry[libraries.size()]), null);
    } catch (JavaModelException e1) {
         e1.printStackTrace();
    }

However I'd like to copy the jtwitter file to the project folder programatically so I could reference it as jtwitter.jar only. Can this be done please?

Thanks a lot and regards, Krt_Malta

Upvotes: 3

Views: 2565

Answers (3)

Markus
Markus

Reputation: 21

IFile.getRawLocationURI() gets you an absolute path

Upvotes: 2

Krt_Malta
Krt_Malta

Reputation: 9465

This did the trick. What I wanted exactly is importing the library into the project and then referencing it from the project not using a reference to an external file.

    InputStream is = new BufferedInputStream(new FileInputStream("C:\\myfolder\\mylibrary.jar"));
    IFile file = project.getFile("mylibrary.jar");
    file.create(is, false, null);

    IPath path = file.getFullPath();
    libraries.add(JavaCore.newLibraryEntry(path, null, null));
    //add libs to project class path
    try {
       javaProject.setRawClasspath(libraries.toArray(new IClasspathEntry[libraries.size()]), null);
    } catch (JavaModelException e1) {
       e1.printStackTrace();
    }

Upvotes: 2

VonC
VonC

Reputation: 1324278

setRawClasspath() is the right method.

However, you need first to copy your jar to the root directory of your project before adding it (with the new path) to the classpath of the project.
That way, the relative path of the jar will be jtwitter.jar.

Upvotes: 0

Related Questions