java把目录下的文件添加到zip包

 

package org.compress.zip;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.CRC32;
import java.util.zip.CheckedOutputStream;

import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipOutputStream;

/**
 * compress the specified basePath(file or directory) to a zip package.
 * @author  zhoubuyue
 */
public class ZipCompress {
	private String basePath;
	private String zipPath;
	
	/**
	 * 
	 * @param basePath:the base path.eg:'D:\\iknow\\'
	 * @param zipPath:the compressed zip file's name and path.eg:'D:\\iknow.zip'
	 */
	public ZipCompress(String basePath,String zipPath){
		this.basePath = trimSlash(basePath);
		this.zipPath = trimSlash(zipPath);
	}
	
	/**
	 * if the path 's last character is '/' or '\' then trim it.
	 * @param path
	 * @return
	 */
	private String trimSlash(String path){
		if(path == null || "".equals(path)){
			return "";
		}
		path = path.replace("/", "\\");
		if(path.endsWith("\\")){
			path = path.substring(0 , path.length() -1);
		}
		return path;
	}
	
	/**
	 * the method provide for foreign transfer.
	 */
	public void compress(){
		ZipOutputStream zipOut = null;
		try{  
            FileOutputStream fileOut = new FileOutputStream(this.zipPath);  
            CheckedOutputStream checkOut = new CheckedOutputStream(fileOut,new CRC32());  
            zipOut = new ZipOutputStream(new BufferedOutputStream(checkOut)); 
            zipOut.setEncoding("gbk");
            zipOut.setComment("this is a iknow exported zip file.");  
            cycleFile(zipOut,this.basePath,"");
        }catch(IOException e){  
            e.printStackTrace();
        }finally{
        	if(zipOut != null){
        		try {
					zipOut.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
        	}
        }
	}
	
	/**
	 * repeatedly transfer the method to visit all of the files listed on the basepath.
	 * @param zipOut
	 * @param filePath
	 * @param relativePath
	 */
	private void cycleFile(ZipOutputStream zipOut,String filePath,String relativePath){
		File file = new File(filePath);
		if(file.isFile()){
			write(zipOut,filePath,relativePath);
		}else{
			File[] children = file.listFiles();
			for(File f : children){
				String tmpFilePath = filePath + "\\" + f.getName();
				String tmpRelativePath = null;
				if("".equals(relativePath)){
					tmpRelativePath = f.getName();
				}else{
					tmpRelativePath = relativePath + "\\" + f.getName();
				}
				cycleFile(zipOut,tmpFilePath,tmpRelativePath);
			}
		}
	}
	
	private void write(ZipOutputStream zipOut,String filePath,String fileName){
		FileInputStream fis = null;
		try {
			zipOut.putNextEntry(new ZipEntry(fileName));
			fis = new FileInputStream(filePath);
			int size = 1024;
			int length = fis.available();
			int len = (length % size == 0) ? length/size : length/size + 1;
			byte[] temp = new byte[size];
	        for( int i = 0 ; i < len ; i++ ){
	        	length = fis.read(temp);
	        	zipOut.write(temp,0,length);
	        }
		}catch (Exception e) {
			e.printStackTrace();
		}finally{
			if(fis != null){
				try {
					fis.close();
				} catch (IOException e) {
					e.printStackTrace();
				}  
			}
		}
	}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Java中可以使用`java.util.zip`来实现根据URL将多个文件zip并进行下载的功能。下面是一个示例代码: ```java import java.io.*; import java.net.URL; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; public class FileZipDownloader { public static void main(String[] args) { String zipUrl = "http://example.com/files.zip"; String[] fileUrls = {"http://example.com/file1.txt", "http://example.com/file2.txt"}; try { // 创建ZipOutputStream FileOutputStream fos = new FileOutputStream("downloaded_files.zip"); ZipOutputStream zos = new ZipOutputStream(fos); // 从URL下载并添加文件zip中 for (String fileUrl : fileUrls) { URL url = new URL(fileUrl); InputStream is = url.openStream(); zos.putNextEntry(new ZipEntry(url.getFile())); byte[] buffer = new byte[1024]; int length; while ((length = is.read(buffer)) > 0) { zos.write(buffer, 0, length); } is.close(); zos.closeEntry(); } // 关闭流 zos.close(); fos.close(); // 下载zip文件 downloadZip(zipUrl); } catch (IOException e) { e.printStackTrace(); } } private static void downloadZip(String url) throws IOException { URL zipUrl = new URL(url); InputStream is = zipUrl.openStream(); FileOutputStream fos = new FileOutputStream("downloaded_files.zip"); byte[] buffer = new byte[1024]; int length; while ((length = is.read(buffer)) > 0) { fos.write(buffer, 0, length); } is.close(); fos.close(); } } ``` 上述代码首先创建了一个`ZipOutputStream`对象,然后依次遍历多个文件的URL,将每个文件下载后添加zip中,并关闭流。最后调用`downloadZip`方法根据zip文件的URL进行下载。请确保提供的URL和文件格式的可用性和正确性。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值