0

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

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

但结果似乎是:

在此处输入图像描述


更新 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>
4

3 回答 3

1

我怀疑问题出在这一行:

IPath path = file.getFullPath();

试试这条线:

IPath path = file.getProjectRelativePath();

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

于 2012-08-06T15:03:00.407 回答
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);
于 2012-08-06T08:08:49.020 回答
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);

更多信息在这里

于 2012-08-06T18:48:32.080 回答