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

    /**
     * 
     * 将文件或文件夹添加到已存在的压缩包
     * 
* @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 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(); } } /** *
     * 输入输出流复制文件
     * 
* @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))