将库添加为“引用库”

时间:2012-08-05 19:06:32

标签: java eclipse eclipse-plugin

我正在尝试以编程方式将库添加到引用的库中。这是我的代码:

String filename = "myfile.jar";
InputStream is;
try {
   is = new BufferedInputStream(new FileInputStream("D:\\" + filename));
   IFile file = project.getFile(filename);
   file.create(is, false, null);

   IPath path = file.getFullPath();                         
   IClasspathEntry[] cpe = javaProject.getRawClasspath();
   List<IClasspathEntry> libraries = Arrays.asList(cpe);                    
   libraries.add(JavaCore.newLibraryEntry(path, null, null));
   try {
        javaProject.setRawClasspath(libraries.toArray(new IClasspathEntry[libraries.size()]), null);
   } catch (JavaModelException e1) {
        e1.printStackTrace();
   }
 } catch (FileNotFoundException e) {
   e.printStackTrace();
 }

但结果似乎是:

enter image description here


更新1。

这是类路径。 .classpath似乎没有改变。

<?xml version="1.0" encoding="UTF-8"?>
<classpath>
    <classpathentry kind="src" path="src"/>
    <classpathentry kind="con"  path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.6"/>
    <classpathentry kind="output" path="bin"/>
</classpath>

3 个答案:

答案 0 :(得分:1)

我怀疑问题出在这一行:

IPath path = file.getFullPath();

请尝试使用此行:

IPath path = file.getProjectRelativePath();

在更改项目构建路径时调试问题的一种好方法是查看项目根目录中的.classpath文件。此文件将向您显示代码所具有的确切效果。然后与手动执行等效操作时获得的效果进行比较。

答案 1 :(得分:0)

以下是如何向项目添加自定义库的代码段。我希望它可以帮助你理解。

// configure class path, source dir and output dir
        final IPath outputpath = project.getFullPath().append(CLASSES);
        final IClasspathEntry classpath1 = JavaCore.newSourceEntry(project.getFullPath().append(customPath));
        final IClasspathEntry[] defaultClasspath = org.eclipse.jdt.ui.PreferenceConstants.getDefaultJRELibrary();
        final IClasspathEntry[] newClasspath = new IClasspathEntry[defaultClasspath.length + 2];
        System.arraycopy(defaultClasspath, 0, newClasspath, 0, defaultClasspath.length);
        newClasspath[defaultClasspath.length] = classpath1;
        javaProject.setRawClasspath(newClasspath, outputpath, null);

答案 2 :(得分:0)

此解决方案有效:

IClasspathEntry[] entries = javaProject.getRawClasspath();
IClasspathEntry[] newEntries = new IClasspathEntry[entries.length + 1];

 System.arraycopy(entries, 0, newEntries, 0, entries.length);

 // add a new entry using the path to the container
 //Path junitPath = new Path("D:\\jarscan.jar");
 IClasspathEntry junitEntry = JavaCore.newLibraryEntry(new Path("D:\\jarscan.jar"), null, null, false);
 newEntries[entries.length] = junitEntry;
 javaProject.setRawClasspath(newEntries, null);

更多信息here