0

I've been trying all morning and I can't figure this out! I'm basing my code off this sample

public void run() throws IOException
{
  Manifest manifest = new Manifest();
  manifest.getMainAttributes().put(Attributes.Name.MANIFEST_VERSION, "1.0");
  JarOutputStream target = new JarOutputStream(new FileOutputStream("output.jar"), manifest);
  add(new File("inputDirectory"), target);
  target.close();
}

private void add(File source, JarOutputStream target) throws IOException
{
  BufferedInputStream in = null;
  try
  {
    if (source.isDirectory())
    {
      String name = source.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);
  return;
}

JarEntry entry = new JarEntry(source.getPath().replace("\\", "/"));
entry.setTime(source.lastModified());
target.putNextEntry(entry);
in = new BufferedInputStream(new FileInputStream(source));

byte[] buffer = new byte[1024];
while (true)
{
  int count = in.read(buffer);
  if (count == -1)
    break;
  target.write(buffer, 0, count);
}
target.closeEntry();
}
finally
   {
    if (in != null)
      in.close();
  }
}

Let's say my directory structure is

- C:/source
-- C:/source/test.txt
--- C:/source/folder/test2.txt
----C:/source/folder/deeper/test3.txt

I want my JAR to be structured as follows

- META-INF/manifest.MF (I've already got this part sorted)
-- test.txt
--- folder (which then contains test2 and a sub folder called deeper which in turn contains test3.txt)

I'm struggling to get the recursion right.

The code sample above creates the C:\source folder in my zip which obviously isn't what I want.

Community
  • 1
  • 1

1 Answers1

0

Use a relative path for the path entry. The line should look like this:

JarEntry entry = new JarEntry(source.getPath().substring(yourRootPath.length()).replace("\\", "/");

where yourRootPath is the path to the directory that is onle level higher than all contents to be included (e.g. your start of recursion).

In your example this will be "C:\"

masinger
  • 775
  • 6
  • 13
  • This partially works. I've actually placed my files in My Documents (C:\Users\ian\Documents\source) and set yourRootPath to `C:\Users\ian\Documents\` and now get the whole Users --> Ian --> Documents placed in the jar as well. – ian edmondson Oct 24 '15 at 13:00
  • Did you change it in both occurances of "new JarEntry(...)"? – masinger Oct 24 '15 at 14:33