用 Java 在 Zip 文件夹中创建文件夹

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16381281/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 22:49:05  来源:igfitidea点击:

Creating Folders in a Zip Folder in Java

javafilezipdirectory

提问by StaticGamedude

My task requires me to save a file directory into a zip folder. My only problem is I need to keep the sub-folders as folders from the main Directory. The file system will look something like

我的任务要求我将文件目录保存到 zip 文件夹中。我唯一的问题是我需要将子文件夹作为主目录中的文件夹。文件系统看起来像

C\Friends
C:\Friends\Person1\Information.txt
C:\Friends\Person2\Information.txt
C:\Friends\Person3\Information.txt

. . .

. . .

Right now I am able to write just the txt files inside of my zip folder, but in my zip folder I need to keep that folder structure. I know the way my code is right now will tell me the file I'm trying to write is closed(No access). My Functions thus far:

现在我只能在我的 zip 文件夹中写入 txt 文件,但在我的 zip 文件夹中我需要保留该文件夹结构。我知道我的代码现在的方式会告诉我我正在尝试写入的文件已关闭(无访问权限)。到目前为止我的功能:

private String userDirectroy = "" //This is set earlier in the program

public void exportFriends(String pathToFile)
    {
        String source = pathToFile + ".zip";

        try
        {


            String sourceDir = userDirectory;
            String zipFile = source;

            try
            {

                    FileOutputStream fout = new FileOutputStream(zipFile);


                    ZipOutputStream zout = new ZipOutputStream(fout);


                    File fileSource = new File(sourceDir);

                    addDirectory(zout, fileSource);


                    zout.close();

                    System.out.println("Zip file has been created!");
            }       
            catch(Exception e)
            {

            }

        }
        catch(Exception e)
        {
            System.err.println("First Function: " + e);

        }
    }

     private static void addDirectory(ZipOutputStream zout, File fileSource) {


         File[] files = fileSource.listFiles();

         System.out.println("Adding directory " + fileSource.getName());

         for(int i=0; i < files.length; i++)
         {

                 if(files[i].isDirectory())
                 {
                     try
                     {
                         byte[] buffer = new byte[1024];
                         FileInputStream fin = new FileInputStream(files[i]);
                         zout.putNextEntry(new ZipEntry(files[i].getName()));

                         int length;

                         while((length = fin.read(buffer)) > 0)
                         {
                            zout.write(buffer, 0, length);
                         }
                     }
                     catch(Exception e)
                     {
                        System.err.println(e); 
                     }
                         addDirectory(zout, files[i]);
                         continue;
                 }


                 try
                 {
                         System.out.println("Adding file " + files[i].getName());

                         //create byte buffer
                         byte[] buffer = new byte[1024];

                         //create object of FileInputStream
                         FileInputStream fin = new FileInputStream(files[i]);

                         zout.putNextEntry(new ZipEntry(files[i].getName()));


                         int length;

                         while((length = fin.read(buffer)) > 0)
                         {
                            zout.write(buffer, 0, length);
                         }



                          zout.closeEntry();

                          //close the InputStream
                          fin.close();

                 }
                 catch(IOException ioe)
                 {
                         System.out.println("IOException :" + ioe);                             
                 }
         }

 }

Any help would be much appreciated. Thank You

任何帮助将非常感激。谢谢

回答by MadProgrammer

For each folder, you need to add a empty ZipEntryof the path.

对于每个文件夹,您需要添加一个空ZipEntry的路径。

For each file, you need supply both the path and file name. This will require you to know the part of the path to strip off, this would be everything after the start directory

对于每个文件,您需要提供路径和文件名。这将要求您知道要剥离的路径部分,这将是启动目录之后的所有内容

Expanded concept

扩展概念

So, from your example, if the start directory is C:\Friends, then the entry for C:\Friends\Person1\Information.txtshould look like Person1\Information.txt

因此,从您的示例中,如果开始目录是C:\Friends,则条目C:\Friends\Person1\Information.txt应如下所示Person1\Information.txt

public void exportFriends(String pathToFile) {

    String source = pathToFile + ".zip";
    try {
        String sourceDir = "C:/Friends";
        String zipFile = source;

        try {
            FileOutputStream fout = new FileOutputStream(zipFile);
            ZipOutputStream zout = new ZipOutputStream(fout);

            File fileSource = new File(sourceDir);

            addDirectory(zout, sourceDir, fileSource);

            zout.close();

            System.out.println("Zip file has been created!");
        } catch (Exception e) {
            e.printStackTrace();
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

public static String getRelativePath(String sourceDir, File file) {
    // Trim off the start of source dir path...
    String path = file.getPath().substring(sourceDir.length());
    if (path.startsWith(File.pathSeparator)) {
        path = path.substring(1);
    }
    return path;
}

private static void addDirectory(ZipOutputStream zout, String sourceDir, File fileSource) throws IOException {
    if (fileSource.isDirectory()) {
        // Add the directory to the zip entry...
        String path = getRelativePath(sourceDir, fileSource);
        if (path.trim().length() > 0) {
            ZipEntry ze = new ZipEntry(getRelativePath(sourceDir, fileSource));
            zout.putNextEntry(ze);
            zout.closeEntry();
        }

        File[] files = fileSource.listFiles();
        System.out.println("Adding directory " + fileSource.getName());
        for (int i = 0; i < files.length; i++) {
            if (files[i].isDirectory()) {
                addDirectory(zout, sourceDir, files[i]);
            } else {

                System.out.println("Adding file " + files[i].getName());

                //create byte buffer
                byte[] buffer = new byte[1024];

                //create object of FileInputStream
                FileInputStream fin = new FileInputStream(files[i]);
                zout.putNextEntry(new ZipEntry(getRelativePath(sourceDir, files[i])));

                int length;

                while ((length = fin.read(buffer)) > 0) {
                    zout.write(buffer, 0, length);
                }
                zout.closeEntry();
                //close the InputStream
                fin.close();
            }
        }
    }
}