Im using the following Code to try an package a directory with all its subdirectories and files into one jar-file.
private void writeFile(JarOutputStream jos, File f) throws IOException {
byte buffer[] = new byte[BUFFER_SIZE];
if (f == null || !f.exists())
return; //
JarEntry jarAdd = new JarEntry(f.getName());
jarAdd.setTime(f.lastModified());
jos.putNextEntry(jarAdd);
if(f.isDirectory()){
File[] files = f.listFiles();
for(int i = 0; i < files.length ; i++){
writeFile(jos,files[i]);
}
}
else{
FileInputStream in = new FileInputStream(f);
while (true) {
int nRead = in.read(buffer, 0, buffer.length);
if (nRead <= 0)
break;
jos.write(buffer, 0, nRead);
}
in.close();
}
}
However FileInputStream does not work on directories, so i assume adding the JarEntry will suffice.
Since I do have another problem, I am not able to see if this assumption is correct.
This problem is that many entries made are duplicate.
When trying to add the structure…
activation
/--activation
/-- somefile.txt
…this code fails, because activation is added twice to the jar.
Since those are different directories nested within each other I do not see why this should not work in some way.
It seems that adding the entry using file.getName() will get entry-ids that do not
differentiate between the directories those files are in.
However when I use
file.getAbsolutePath()
for example, the jar structure is messed up with
directories like “C_” and the contained files are not readable anymore.
Can anyone recommend a way to package directory structures in a jar file correctly?
Note that a
JarEntryrepresenting a directory (folder) must end with a slash (“/“) in order to be treated as such; otherwise it will be considered a plain file.