0

I have a program in Java that zip all the files and subdirectories of a directory. It creates a zip file with the absolute path, for example c:\dir1\dirzip\, but I want that it creates the file with only de files and subdirectories, not the absolute path. CAn anaybode help me , please?? This is my code:

import java.io.*;
import java.util.zip.*;

public class zip {

    public static void main(String argv[]) {
        try {

            ZipOutputStream zos =
                new ZipOutputStream(new FileOutputStream(
                    "c:\\pruebazip\\dancedragons.zip"));

            zipDir("c:\\pruebazip\\dancedragons\\", zos);

            zos.close();
        }
        catch (Exception e) {

        }
    }

    public static void zipDir(String dir2zip, ZipOutputStream zos) {
        try {

            File zipDir = new File(dir2zip);
            // lista del contenido del directorio
            String[] dirList = zipDir.list();
            // System.out.println(dirList[1]);
            byte[] readBuffer = new byte[2156];
            int bytesIn = 0;

            System.out.println(dirList.length);
            // recorro el directorio y añado los archivos al zip
            for (int i = 0; i < dirList.length; i++) {
                File f = new File(zipDir, dirList[i]);
                if (f.isDirectory()) {

                    String filePath = f.getPath();
                    zipDir(filePath, zos);

                    System.out.println(filePath);
                    continue;
                }

                FileInputStream fis = new FileInputStream(f);

                ZipEntry anEntry = new ZipEntry(f.getPath());

                zos.putNextEntry(anEntry);

                while ((bytesIn = fis.read(readBuffer)) != -1) {
                    zos.write(readBuffer, 0, bytesIn);
                }

                fis.close();
            }
        }
        catch (Exception e) {
            // handle exception
        }

    }

}
Nick Garvey
  • 2,980
  • 24
  • 31
Migua
  • 575
  • 1
  • 10
  • 17
  • possible duplicate of [java.util.zip - Recreating directory structure](http://stackoverflow.com/questions/1399126/java-util-zip-recreating-directory-structure) – McDowell Jan 30 '12 at 14:14

2 Answers2

8

If you'd like for each zip entry to be stored in the directory structure relative to the zipped folder, then instead of constructing the ZipEntry with the files full path:

new ZipEntry(f.getPath());

Construct it with its path relative to the zipped directory:

String relativePath = zipDir.toURI().relativize(f.toURI()).getPath();
new ZipEntry(relativePath);
noamt
  • 7,397
  • 2
  • 37
  • 59
0

Your issue may be the statement

new ZipEntry(f.getPath())

Double-check that f.getPath() is not an absolute path like C:\dir\....

You may want something like new ZipEntry(dirList[i]) instead.

wrschneider
  • 17,913
  • 16
  • 96
  • 176