【问题标题】:Paste files inside a zip folder in java将文件粘贴到 java 中的 zip 文件夹中
【发布时间】:2023-01-14 05:04:54
【问题描述】:

我想弄清楚如何将文件粘贴到 .zip 文件内的文件夹中。我使用下面的代码只是将文件添加到 zip 中,而不是其中的特定文件夹。我不允许解压缩此文件。我有一些基本的文本文件来替换 zip 中已经存在的同名文件。

如何修改此方法以选择 zip 中的特定文件夹?谢谢!

 public static void addFilesToExistingZip(File zipFile, File[] files) throws IOException {
        File tempFile = File.createTempFile(zipFile.getName(), null);
        tempFile.delete();
        
        zipFile.renameTo(tempFile);
        
        byte[] buf = new byte[1024];
        
        ZipInputStream zin = new ZipInputStream(new FileInputStream(tempFile));
        ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipFile));
        ZipEntry entry = zin.getNextEntry();
        
        while (entry != null) {
            String name = entry.getName();
            boolean notInFiles = true;
            for (File f : files) {
                if (f.getName().equals(name)) {
                    notInFiles = false;
                    break;
                }
            }
            
            if (notInFiles) { // Add ZIP entry to output stream.
                out.putNextEntry(new ZipEntry(name)); // Transfer bytes from the ZIP file to the output file
                int len;
                while ((len = zin.read(buf)) > 0) {
                    out.write(buf, 0, len);
                }
            }
            
            entry = zin.getNextEntry();
        } // Close the streams
        
        zin.close(); // Compress the files
        
        for (int i = 0; i < files.length; i++) {
            InputStream in = new FileInputStream(files[i]); // Add ZIP entry to output stream.
            out.putNextEntry(new ZipEntry(files[i].getName())); // Transfer bytes from the file to the ZIP file
            
            int len;
            while ((len = in.read(buf)) > 0) {
                out.write(buf, 0, len);
            } // Complete the entry
            
            out.closeEntry();
            in.close();
        } // Complete the ZIP file
        
        out.close();
        tempFile.delete();
    }

【问题讨论】:

  • 您可以将名称设置为类似 folder\folder2\file.txt 的名称,并将路径拆分为不同的段(字符串数组),这样,您就可以在使用 File.isDirectory() 方法检查它是否是一个目录后进入 ZipEntry。我仍然不确定这是否有效。 PS:您应该查看ZipFile 课程。

标签: java file zip


【解决方案1】:

解压缩文件,将文件粘贴到解压缩版本中,然后压缩解压缩版本并删除副本。这可能听起来很时髦,但它会起作用。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-23
    • 1970-01-01
    • 2020-05-20
    • 2019-11-18
    • 1970-01-01
    • 2021-02-11
    相关资源
    最近更新 更多