Search code examples
javazipzip4j

Exempt files and folder with Zip4j in Java


I have created a backup system which I sell called EasyBackup for servers. The system works great, and it uses zipped files. Someone requested that I add a feature to add a password to the zipped folder, but I could not find a way to do that with Java's zip utility classes, so I decided to use Zip4j.

Zip4j adds passwords perfectly, but when I add a folder, it adds all files and subfolders.

I have an option for users to exempt files and folders, so I need a way to retain this ability.

How can I exempt files and folders with Zip4J. Is there a way to add folders and files manually so the children are not added?

If not, would modifying the sourcecode for Zip4J be practical? Is there another library that does this already?


Solution

  • I solved this by modifying Zip4j. I made a crude change which kind of abuses static, but it is in a Utility class, so I am not too concerned.

    I made the following changes in the Zip4jUtil class, and I created an interface called ExemptFileHandler with one method:

    public boolean isExempt(File file);

    Then in the Zip4jUtil class I made the following static object:

    private static ExemptFileHandler handler;

    Finially, I modified the getFilesInDirectoryRec recursive method as so:

    for(int i = 0; i < filesDirs.size(); i++) {
        File file = (File)filesDirs.get(i);
        if (file.isHidden() && !readHiddenFiles) {
            return result;
        }
        if(handler == null || !handler.isExempt(file)) {
            result.add(file);
            if (file.isDirectory()) {
                List deeperList = getFilesInDirectoryRec(file, readHiddenFiles);
                result.addAll(deeperList);
            }
        }
    }
    

    This now enables me to exempt files and folders. This is a crude fix. With this fix, I am only able to create one zipped file at a time, unless I am okay with exempt files being the same for each zipped file. I could modify it further, but this is all I need to make it work, and it does.