如何在 Java 中压缩目录的内容 [英] How to zip the content of a directory in Java

查看:28
本文介绍了如何在 Java 中压缩目录的内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 java 下面使用,但是当它压缩时,它会创建一个目录并将该目录中的所有内容压缩.例如.如果我有一个名为Directory"的文件夹并且我想将内容压缩到一个压缩文件中,则在压缩文件中它会创建一个文件夹 testZip 并在其中包含文件.我需要压缩文件中的所有文件,而不是父目录中的所有文件.请帮忙.或建议是否有任何其他方式.

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

推荐答案

所以,如果我理解正确的话,您想要的是,而不是出现在 Zip 文件中的目标文件夹,其中的所有文件都应以/" 在 Zip 文件中.

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.

例如,如果你有

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

Zip 文件的内容应包含

The contents of the Zip file should contain

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

为此,您需要保留对start"文件夹的引用,并将其路径从您添加的文件中删除,以创建 ZipEntry.

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.

为简单起见,我更改了您的代码以支持 File 而不是 String,它只是让整个事情变得不那么混乱.

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 是初始文件夹(在您的示例中为 C:\\Drive\\temp\\testZip"),srcFile 是要添加的文件.

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

可运行示例...

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

我还使用 try-with-resources 清理了您的资源管理

这篇关于如何在 Java 中压缩目录的内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆