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

标签 java file zip directory

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

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

。 。 .

现在我只能在 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);                             
                 }
         }

 }

任何帮助将不胜感激。谢谢您

最佳答案

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

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

扩展概念

因此,根据您的示例,如果起始目录为 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();
            }
        }
    }
}

关于java - 用 Java 在 Zip 文件夹中创建文件夹,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16381281/

相关文章:

ruby - 使用 Ruby 逐行读取、编辑和写入文本文件

php - Laravel 文件上传只需将文件名发送到 Controller

symfony - 如何将 Symfony 发行版下载为 Zip 存档?

python - 在文件中查找给定单词的字谜

c# - 如何自动更改新 .zip 文件的名称?

Java:从 InputStream 读取并不总是读取相同数量的数据

java - Hystrix 仪表板始终显示加载屏幕

java - 包含实例的匿名类

java - 将变量声明为 Enum<EnumType> 和 EnumType 之间的区别

java - XSLT 将计数器与字段名称连接起来以使其动态化