批量压缩文件[文件夹]

/**
	 * 压缩文件-由于out要在递归调用外,所以封装一个方法用来
	 * 调用ZipFiles(ZipOutputStream out,String path,File... srcFiles)
	 * @param zip
	 * @param path
	 * @param srcFiles
	 * @throws IOException
	 * @author [email protected]
	 */
	public static void ZipFiles(File zip,String path,List<File> srcFiles) throws IOException{
		ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zip));
		ZipFiles(out,path,srcFiles);
		out.close();
		//System.out.println("*****************压缩完毕*******************");
	}
	/**
	 * 压缩文件-File
	 * @param zipFile  zip文件
	 * @param srcFiles 被压缩源文件
	 * @author [email protected]
	 */
	public static void ZipFiles(ZipOutputStream out,String path,List<File> srcFiles){
		path = path.replaceAll("\\*", "/");
		if(!path.endsWith("/")){
			path+="/";
		}
		byte[] buf = new byte[1024];
		try {
			for(File f:srcFiles){
				if(f.isDirectory()){
					File[] files = f.listFiles();
					String srcPath = f.getName();
					srcPath = srcPath.replaceAll("\\*", "/");
					if(!srcPath.endsWith("/")){
						srcPath+="/";
					}
					out.putNextEntry(new ZipEntry(path+srcPath));
					ZipFiles(out,path+srcPath,Arrays.asList(files));
				}
				else{
					FileInputStream in = new FileInputStream(f);
					//System.out.println(path + srcFiles[i].getName());
					out.putNextEntry(new ZipEntry(path + f.getName()));
					int len;
					while((len=in.read(buf))>0){
						out.write(buf,0,len);
					}
					out.closeEntry();
					in.close();
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public static void main(String[] args) throws IOException {
		//zipFiles(new File[]{new File("D:\\WS\\demo.js"),new File("D:\\WS\\111111111111111111.txt")}, new File("D:\\XXXX.zip"));
		/** 
         * 压缩文件 
         */  
        File[] files = new File[]{new File("D:\\WS"),new File("D:\\temp\\temp\\OFFICE2013激活工具Microsoft Toolkit_2.4.9"),new File("D:\\XXXX.zip")};  
        
        File zip = new File("d:/压缩.zip");  
        ZipFiles(zip,"",Arrays.asList(files));  
	}

 

你可能感兴趣的:(文件夹)