Migua
Migua

Reputation: 555

zip directory with files and subdirectories without the absolute path in Java

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
        }

    }

}

Upvotes: 0

Views: 8512

Answers (2)

noamt
noamt

Reputation: 7815

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);

Upvotes: 8

wrschneider
wrschneider

Reputation: 18770

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.

Upvotes: 0

Related Questions