1

I have a prorgam thats generating source code and want to compile this source code during the java-runtime execution like:

generateSource()
compileSource()

I use the JavaCompiler from ToolProvider:

ArrayList<String> optionList = new ArrayList<String>();
System.out.println("Retrieve dependendcy Jars");
ArrayList<File> jarfiles = getJarFiles(this.libdir);
String libpath = System.getProperty("java.class.path") + convertJarFilesToClassPath(jarfiles);
optionList.addAll(Arrays.asList("-d", this.genClassDir ));
optionList.addAll(Arrays.asList("-classpath", libpath));

ArrayList<File> files1 =  getSourceFiles(this.genCodeDir); 
Iterable<? extends JavaFileObject> compilationUnits1 = fileManager.getJavaFileObjectsFromFiles(files1);
JavaCompiler.CompilationTask task = compiler.getTask(null ,fileManager , null, optionList, null, compilationUnits1 );
task.call();

Now the important line is where i add the -d classdirectory in the optionlist.

I have this genClassDir /gen/classes where all my .class files are inside including subdirs.

Now the problme in my jar file is, that the class files are having the genClassDir as prefix before the package structure.

./gen/classes/foo/
./gen/classes/foo/bar/

instead of

/foo
/foo/bar

or without the leading slash.

I am packaging the jar like in the first answer from How to use JarOutputStream to create a JAR file?

Is there a way i get only the package structure of the class files in my jar?

Community
  • 1
  • 1
Gobliins
  • 3,848
  • 16
  • 67
  • 122

1 Answers1

0

You could add a basePath parameter to the add()-method of the solution shown in the other question and the strip the base path from each file name before creating the Jarentry

private void add(File source, String basePath, JarOutputStream target) throws IOException
{
    //...
    name = name.replaceFirst(basePath, "");
    JarEntry entry = new JarEntry(name);
    //...
}

Adjust the replacement as necessary (leading/trailing slashes, backslashes instead of slashes, etc.)

Usage:

add(new File("gen/classes/test.class", "gen/classes", new JarOutputStream(...));
Soana
  • 711
  • 7
  • 15