java - 压缩根文件夹内容,但 zip 文件没有根目录

标签 java zip java-io apache-commons-io

我有以下文件夹结构:

RootFolder
|
|
| -->F1-->F1.1-->t1.txt,t2.txt
  -->F2-->F2.2-->t3.txt

I have succeed,using the following code,to get the following zip file:

result.zip--> that contains:

RootFolder
|
|
| -->F1-->F1.1-->t1.txt,t2.txt
  -->F2-->F2.2-->t3.txt

I need to create a zip file that has the whole "RootFolder" content without creating a root folder"RootFolder";

I mean I need the result to be like:

result.zip--> that contains:

|
|
| -->F1-->F1.1-->t1.txt,t2.txt
  -->F2-->F2.2-->t3.txt
public static void main(String[] args) throws Exception {
    zipFolder("c:/new/RootFolder", "c:/new/result.zip");
}


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

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

    addFolderToZip("", srcFolder, zip);
    zip.flush();
    zip.close();
}

static private void addFileToZip(String path, String srcFile,
        ZipOutputStream zip) throws IOException, FileNotFoundException {

    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);
        }
        in.close();
    }
}

    static public void addFolderToZip(String path, String srcFolder,
            ZipOutputStream zip) throws IOException, FileNotFoundException {
        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);
        }
    }
}

最佳答案

您需要做的是添加文件,而不是从根文件夹开始,而是从其内容开始。

类似于:

filelist = getFileList(rootFolder)  
foreach(File f : filelist){  
    addFolderToZip(f)
}

抱歉,伪代码,不记得原始函数名称,现在无法检查它们,但可以轻松通过谷歌搜索它们。

重点是跳过在根文件夹的存档中创建文件夹的步骤。

关于java - 压缩根文件夹内容,但 zip 文件没有根目录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15066445/

相关文章:

java - 使用字节数组创建 AudioInputStream

java - 我们如何使用 SortedMap 接口(interface)对 Map 进行排序?

java - 如何在 Java 中比较字符串?

delphi - 在 Lazarus 中使用 zlibar 将 zip 文件提取到 TStream

r - download.file() 在 Windows 上生成 "invalid"zip 文件,但在 Mac 上工作正常

java - 读取 .txt 文件的内容并将其显示在多个文本区域

java - 差异错误代码或异常

java - 如何使用一个接口(interface)作为另一个接口(interface)函数的参数?

java - 如何修复 org.apache.commons.compress.archivers.zip.UnsupportedZipFeatureException(epub mimetype)?

java - 当我可以使用后者创建文件时,为什么我应该创建 File 对象,然后在 FileWriter 或 PrintWriter 中使用它?