How do you make a Zip/Jar in Java that will not contain the absolute pathname?
I'm generating a .jar file in Java, but the .jar contains an absolute pathname of where it is in the system (/tmp/tempXXX/foo instead of /foo). The tree is like this:
Code :
.
|-- META-INF
|-|- ....
|-- tmp
|-|- tempXXX
|-|-|- foo
|-|-|- bar
Instead of this:
Code :
.
|-- META-INF
|-|- ....
|-- foo
|-- bar
Is it possible to fix this? Here is the function that makes it:
Code :
public static void add(File source, JarOutputStream target, String removeme)
throws IOException
{
BufferedInputStream in = null;
try
{
File source2 = source;
if (source.isDirectory())
{
String name = source2.getPath().replace("\\", "/");
if (!name.isEmpty())
{
if (!name.endsWith("/"))
name += "/";
JarEntry entry = new JarEntry(name);
entry.setTime(source.lastModified());
target.putNextEntry(entry);
target.closeEntry();
}
for (File nestedFile : source.listFiles())
add(nestedFile, target, removeme);
return;
}
JarEntry entry = new JarEntry(source2.getPath().replace("\\", "/"));
entry.setTime(source.lastModified());
target.putNextEntry(entry);
in = new BufferedInputStream(new FileInputStream(source));
byte[] buffer = new byte[2048];
while (true)
{
int count = in.read(buffer);
if (count == -1)
break;
target.write(buffer, 0, count);
}
target.closeEntry();
}
finally
{
if (in != null)
in.close();
}
}
The source2 variable was made for modifying the path, but when modifying, it gave an "Invalid .jar file" error.
The modification was this:
Code :
File source2 = new File(source.getPath().replaceAll("^" + removeme, ""));
Re: How do you make a Zip/Jar in Java that will not contain the absolute pathname?
I've never seen a Jar being created this way, so I'm only guessing, but have you tried removing removeme (which I assume is the pathname leading up to the directory you're working with) from the String name instead of from the File? And in that case, wouldn't remove me just be your source path?