美文网首页
将文件或文件夹添加到已存在的压缩包(rar、zip)

将文件或文件夹添加到已存在的压缩包(rar、zip)

作者: 李北北 | 来源:发表于2018-11-05 20:21 被阅读0次
    /**
     * <pre>
     * 将文件或文件夹添加到已存在的压缩包
     * </pre>
     * @author 北北
     * @date 2018年11月5日下午8:19:23
     * @param zipPath
     * @param addFilePath
     */
    public static void addToZip(String zipPath, String addFilePath) {
        try {
            File oldFile = new File(zipPath);
            if(!oldFile.exists()){
                createZip(oldFile.getParent(), oldFile.getName());
            }
            
            //创建一个临时的新压缩包
            String appendPath = oldFile.getParent() + "/" + oldFile.getName().replace(".rar", "").replace(".zip", "") + "_append" + ".rar";
            File appendFile = new File(appendPath);
            ZipOutputStream appendOut = new ZipOutputStream(new FileOutputStream(appendPath));
            
            //从已存在的压缩包中复制内容到新压缩包
            ZipFile zpFile = new ZipFile(zipPath);
            Enumeration<? extends ZipEntry> entries = zpFile.entries();
            while (entries.hasMoreElements()) {
                ZipEntry e = entries.nextElement();
                System.out.println("copy: " + e.getName());
                appendOut.putNextEntry(e);
                if (!e.isDirectory()) {
                    copy(zpFile.getInputStream(e), appendOut);
                }
                appendOut.closeEntry();
            }
            
            //将需要压缩的文件或文件夹压缩到新压缩包内
            compress(new File(addFilePath), appendOut, "");
            
            //关闭流
            zpFile.close();
            appendOut.close();
            
            //在关闭流后才能执行删除\改名操作
            oldFile.delete();//删除旧压缩包
            appendFile.renameTo(oldFile);//将新压缩包更名为原来的压缩包名字
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * <pre>
     * 输入输出流复制文件
     * </pre>
     * @author 北北
     * @date 2018年11月5日下午7:48:54
     * @param input
     * @param output
     * @throws IOException
     */
    public static void copy(InputStream input, OutputStream output) throws IOException {
        int bytesRead;
        while ((bytesRead = input.read(BUFFER_ARR))!= -1) {
            output.write(BUFFER_ARR, 0, bytesRead);
        }
    }

    /**4MB buffer*/ 
    private static final byte[] BUFFER_ARR = new byte[4096 * 1024];

相关文章

网友评论

      本文标题:将文件或文件夹添加到已存在的压缩包(rar、zip)

      本文链接:https://www.haomeiwen.com/subject/agrexqtx.html