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:
. |-- META-INF |-|- .... |-- tmp |-|- tempXXX |-|-|- foo |-|-|- bar
Instead of this:
. |-- META-INF |-|- .... |-- foo |-- bar
Is it possible to fix this? Here is the function that makes it:
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:
File source2 = new File(source.getPath().replaceAll("^" + removeme, ""));