Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to zip the content of a directory in Java

Tags:

java

zip

I am using below java, but when it zips, it creates a directory and zips all contents inside that directory. For ex. if I have a folder named 'Directory' and I want to zip the content to a Zipped file, inside the zipped file it creates a folder testZip and have files inside that. I need all files inside the zipped file, not inside a parent directory. Please help. or suggest if there is any other way.

package folderZip;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;

import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public class ZipFolder {
    public ZipFolder() {  
    }  


    public static void main(String[] args) throws Exception {
        ZipFolder obj = new ZipFolder();
        obj.zipFolder("C:\\Drive\\temp\\testZip","C:\\Drive\\temp\\FolderZiper.zip");       
    }


     public void zipFolder(String srcFolder,
                                 String destZipFile) throws Exception {
        ZipOutputStream zip = null;
        FileOutputStream fileWriter = null;

        fileWriter = new FileOutputStream(destZipFile);
        zip = new ZipOutputStream(fileWriter);

        addFolderToZip("", srcFolder, zip);

        zip.flush();
        zip.close();

    }

    private void addFileToZip(String path, String srcFile,
                                     ZipOutputStream zip) throws Exception {

        File folder = new File(srcFile);
        if (folder.isDirectory()) {
            addFolderToZip(path, srcFile, zip);
        } else {
            byte[] buf = new byte[1024];
            int len;
            FileInputStream in = new FileInputStream(srcFile);
            zip.putNextEntry(new ZipEntry(path + "/" + folder.getName()));
            while ((len = in.read(buf)) > 0) {
                zip.write(buf, 0, len);
            }
        }
    }

    private void addFolderToZip(String path, String srcFolder,
                                       ZipOutputStream zip) throws Exception {
        File folder = new File(srcFolder);

        for (String fileName : folder.list()) {
            if (path.equals("")) {
                addFileToZip(folder.getName(), srcFolder + "/" + fileName,
                             zip);
            } else {
                addFileToZip(path + "/" + folder.getName(),
                             srcFolder + "/" + fileName, zip);
            }
        }
    }
}
like image 847
Vivek Vishal Avatar asked Aug 14 '18 03:08

Vivek Vishal


1 Answers

So, if I understand correctly, what you want is, instead of the target folder appearing in the Zip file, all the files within it should start at "/" in the Zip file.

For example, if you had

FolderToZip/
    TestFile1.txt
    TestFile2.txt
    TestFile3.txt
    SomeSubFolder/
        TestFile4.txt
        TestFile5.txt
        TestFile6.txt

The contents of the Zip file should contain

TestFile1.txt
TestFile2.txt
TestFile3.txt
SomeSubFolder/
    TestFile4.txt
    TestFile5.txt
    TestFile6.txt

To do this, you need to keep a reference to the "start" folder and strip it's path off the files you are adding, to create the ZipEntry.

For simplicity, I changed your code to support File instead of String, it just makes the whole thing a lot less messy.

But the magic appears here...

FileInputStream in = new FileInputStream(srcFile);
String name = srcFile.getPath();
name = name.replace(rootPath.getPath(), "");
System.out.println("Zip " + srcFile + "\n to " + name);
zip.putNextEntry(new ZipEntry(name));

rootPath is the initial folder (C:\\Drive\\temp\\testZip" in your example), srcFile is the file to be added.

Runnable example...

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;


public class ZipFolder {

    public ZipFolder() {
    }

    public static void main(String[] args) throws Exception {
        ZipFolder obj = new ZipFolder();
        obj.zipFolder(new File("/Users/shanewhitehead/exports"),
                new File("FolderZiper.zip"));
    }

    public void zipFolder(File srcFolder, File destZipFile) throws Exception {
        try (FileOutputStream fileWriter = new FileOutputStream(destZipFile);
                ZipOutputStream zip = new ZipOutputStream(fileWriter)) {

            addFolderToZip(srcFolder, srcFolder, zip);
        }
    }

    private void addFileToZip(File rootPath, File srcFile, ZipOutputStream zip) throws Exception {

        if (srcFile.isDirectory()) {
            addFolderToZip(rootPath, srcFile, zip);
        } else {
            byte[] buf = new byte[1024];
            int len;
            try (FileInputStream in = new FileInputStream(srcFile)) {
                String name = srcFile.getPath();
                name = name.replace(rootPath.getPath(), "");
                System.out.println("Zip " + srcFile + "\n to " + name);
                zip.putNextEntry(new ZipEntry(name));
                while ((len = in.read(buf)) > 0) {
                    zip.write(buf, 0, len);
                }
            }
        }
    }

    private void addFolderToZip(File rootPath, File srcFolder, ZipOutputStream zip) throws Exception {
        for (File fileName : srcFolder.listFiles()) {
            addFileToZip(rootPath, fileName, zip);
        }
    }
}

I also cleaned up your resource management, using try-with-resources

like image 106
MadProgrammer Avatar answered Sep 21 '22 02:09

MadProgrammer