Importing libraries in Eclipse programmatically

房东的猫 提交于 2020-01-23 09:52:08

问题


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


回答1:


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();
    }



回答2:


IFile.getRawLocationURI() gets you an absolute path




回答3:


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.



来源:https://stackoverflow.com/questions/2531277/importing-libraries-in-eclipse-programmatically

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!