views:

175

answers:

2

Hi,

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

A: 

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.

VonC
Yes, any idea how I can copy it please?
Krt_Malta
+1  A: 

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();
    }
Krt_Malta
Good solution (Creating a IFile from the project with an absolute path) +1
VonC