java 解压zip文件到所在的文件夹下并删除压缩包

      /**
     * 解压到指定目录
     *
     * @param zipPath 待解压的zip文件
     * @param descDir 指定目录
     */
    public void unZipFiles(String zipPath, String descDir) {
        unZipFiles(new File(zipPath), descDir);
    }

    /**
     * 解压文件到指定目录
     * 解压后的文件名,和之前一致
     *
     * @param zipFile 待解压的zip文件
     * @param descDir 指定目录
     */
    public void unZipFiles(File zipFile, String descDir) {
        try (ZipFile zip = new ZipFile(zipFile, Charset.forName("GBK"));) {
            String name = zip.getName().substring(zip.getName().lastIndexOf('/') + 1, zip.getName().lastIndexOf('.'));
            File pathFile = new File(descDir + name);
            if (!pathFile.exists()) {
                pathFile.mkdirs();
            }
            for (Enumeration<? extends ZipEntry> entries = zip.entries(); entries.hasMoreElements(); ) {
                ZipEntry entry = entries.nextElement();
                String zipEntryName = entry.getName();

                try (InputStream in = zip.getInputStream(entry);) {
                    String outPath = (descDir + name + "/" + zipEntryName).replaceAll("\\*", "/");
                    // 判断路径是否存在,不存在则创建文件路径
                    File file = new File(outPath.substring(0, outPath.lastIndexOf('/')));
                    if (!file.exists()) {
                        file.mkdirs();
                    }
                    // 判断文件全路径是否为文件夹,如果是上面已经上传,不需要解压
                    if (new File(outPath).isDirectory()) {
                        continue;
                    }

                    try (FileOutputStream out = new FileOutputStream(outPath);) {
                        byte[] buf1 = new byte[1024];
                        int len;
                        while ((len = in.read(buf1)) > 0) {
                            out.write(buf1, 0, len);
                        }
                    } catch (FileNotFoundException e) {
                        throw new RuntimeException(e);
                    }
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }

            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }
    
    /**
     * 把目录下的所有文件移动到指定文件夹
     * @param sourceDir 源文件夹
     * @param source 指定文件夹
     */
    private void moveFiles(File sourceDir, File source) {
        File[] files = sourceDir.listFiles();
        if (files != null) {
            for (File file : files) {
                if (file.isDirectory()) {
                    moveFiles(file, source);
                    // 检查文件夹是否为空
                    if (file.list().length == 0) {
                        file.delete();
                    }
                } else {
                    try {
                        Files.move(file.toPath(), Paths.get(source.toString() , file.getName()) , StandardCopyOption.REPLACE_EXISTING);
                    } catch (IOException e) {
                        throw new RuntimeException(e);
                    }
                }
            }
        }
    }

调用的代码,先解压到指定文件夹,删除压缩包,然后把这个文件夹的所有文件都提取到这个文件夹根目录下,删除空目录

    if (fileName != null && fileName.endsWith(".zip")) {
                // 处理ZIP文件
                Path zipFile = Paths.get(filePathStr);
                Path parentDir = zipFile.getParent(); // zip 所在目录
                this.unZipFiles(filePathStr, "");
                Files.delete(Paths.get(filePathStr));
                this.moveFiles(parentDir.toFile(), parentDir.toFile());
            }
你可以使用JavaZipInputStream和ZipOutputStream来实现这个功能。具体步骤如下: 1. 使用ZipInputStream读取zip压缩包中的所有文件文件夹。 2. 找到要替换的文件夹在其中找到要替换的文件。 3. 使用ZipOutputStream创建一个新的zip压缩包将原始zip压缩包中除要替换的文件夹之外的所有内容写入新的zip压缩包中。 4. 将要替换的文件夹中的要替换的文件写入新的zip压缩包中。 5. 关闭ZipInputStream和ZipOutputStream,删除原始zip压缩包,将新的zip压缩包重命名为原始zip压缩包的名称。 下面是一个简单的示例代码,可以帮助你开始实现这个功能: ```java import java.io.*; import java.util.zip.*; public class ReplaceFileInZip { public static void main(String[] args) throws IOException { File zipFile = new File("test.zip"); File tempFile = new File("temp.zip"); String folderName = "folder"; String fileName = "file.txt"; String replacementFile = "replacement.txt"; // Create input stream for original zip file ZipInputStream zis = new ZipInputStream(new FileInputStream(zipFile)); // Create output stream for temporary zip file ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(tempFile)); // Copy all entries from original zip file to temporary zip file, except the specified folder and file ZipEntry entry; while ((entry = zis.getNextEntry()) != null) { String name = entry.getName(); if (!name.startsWith(folderName + "/") && !name.equals(fileName)) { zos.putNextEntry(new ZipEntry(name)); byte[] buffer = new byte[1024]; int len; while ((len = zis.read(buffer)) > 0) { zos.write(buffer, 0, len); } } } // Add replacement file to temporary zip file ZipEntry replacementEntry = new ZipEntry(folderName + "/" + fileName); zos.putNextEntry(replacementEntry); FileInputStream fis = new FileInputStream(replacementFile); byte[] buffer = new byte[1024]; int len; while ((len = fis.read(buffer)) > 0) { zos.write(buffer, 0, len); } fis.close(); // Close streams zis.close(); zos.close(); // Replace original zip file with temporary zip file zipFile.delete(); tempFile.renameTo(zipFile); } } ``` 在这个示例代码中,我们假设要替换的文件夹名称为"folder",要替换的文件名为"file.txt",替换文件的名称为"replacement.txt"。你需要将这些值替换为你实际使用的名称。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值