java实现上传zip解压及判断压缩包文件夹功能

  • Post author:
  • Post category:java


直接上Service,通过代码看思路贯穿整个功能,很多工具类可以复用,文件路径可以去看我博客里的


(使用ResourceBundle国际化资源文件读取properties详解) 这篇制作方法


url:


https://blog.csdn.net/qq_17025903/article/details/75949066

html页面

 <span>ZIP:</span> <input type="file" style="width: 170px"  name="hostFileBatch"/><span id="hostCheckResult"></span><br/>  
 <input type="button" value="确认上传" onclick="checkHostBatchRun()"/> 
 <input type="button" value="运行"  onclick="hostRun()" id="hostRunResult" disabled="disabled" > 
 <span id="hostResult"></span>

页面js

function checkHostBatchRun(){
	
if(confirm("上传重名文件将会替换掉原有文件,是否继续上传?")){
	//年
	var hostYear=$("#hostYear").val();
	//季度
	var quarter=$("#hostQuarter").find("option:selected").text();

 	$.ajax({
		type : "POST",
		cache : false,
		dataType : "json",
		data:new FormData($('#hostUploadForm')[0]),
        processData: false,//用于对data参数进行序列化处理 这里必须false
        contentType: false, //必须 ?hostYear="+hostYear+"&quarter="+quarter"
		url : "../uploadController/hostUploadZipBatchRun.htm?hostYear="+hostYear+"&&quarter="+quarter+" ",
		success : function(obj) {
			/* alert(obj.data.msg); */
			var result=obj.data.msg;
			if(result==true){
				$("#hostCheckResult").text("上传成功!").css("color","blue");
				$("#hostRunResult").attr("disabled",false);
			}else{
				$("#hostCheckResult").text("上传失败!").css("color","red");
			}
			
		}
	});	
   }
	
}	

Service

		//创建解析器
		MultipartHttpServletRequest mh=(MultipartHttpServletRequest) request;
		//获得文件  
		CommonsMultipartFile cmf=(CommonsMultipartFile) mh.getFile("hostFileBatch");
		//获得原始文件名
		String oriName=cmf.getOriginalFilename(); 
		//拼接年+月
		String path=hostYear.concat(quarter);
//		String path=String.valueOf(year).concat(String.valueOf(month));
		String savePath=Commons.HOST_UPLOAD_PATH+"\\"+path; //保存的路径
//		File storeDirectory=new File(savePath);  
		//判断是不是zip文件
		if(oriName.matches(".*.zip")) {		
			//判断文件目录是否存在
			File file=new File(savePath);
			//不存在 
			if(!file.exists()) {
				//创建文件夹
				file.mkdirs();
			}else {	
				//文件存在则删除
				deleteDir(file);
//				file.delete();
				file.mkdirs(); 
				//删除文件原始路径
				int deletePath=uploadZipDao.deleteOldFile(oriName,savePath);
			}
			//获取文件
			FileItem fileItem=cmf.getFileItem();  
			try {	
                //文件保存到目录然后解压↓
				fileItem.write(new File(file,oriName));
				//解压文件到指定目录
				FileUnZip.zipToFile(oriName, savePath);
                //删除原上传的文件
				FileUtil.delFile(savePath+File.separator+oriName);
			} catch (Exception e){
				e.printStackTrace();  
				new File(savePath,oriName).delete();  
			}
			fileItem.delete();	
			//保存路径文件名
			boolean result=addPath(oriName,savePath);
			if(result==true) {
				//执行批处理	
				return true;		
			}
			return false;
		}else {
			//不是zip则返回false
			return false;
		}	
	}

解压工具类

package cn.secure.util;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Enumeration;

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

public class FileUnZip {
	/**
     * 解压zip文件
     * @author 于公成
     * @param sourceFile,待解压的zip文件;
     *        toFolder,解压后的存放路径
     * @throws Exception
     **/

	public static void zipToFile(String sourceFile, String toFolder) throws Exception {
			String toDisk = toFolder;// 接收解压后的存放路径
			ZipFile zfile = new ZipFile(sourceFile, "gbk");// 连接待解压文件 "utf-8"会乱码
			Enumeration zList = zfile.getEntries();// 得到zip包里的所有元素
			ZipEntry ze = null;
			byte[] buf = new byte[1024];
			while (zList.hasMoreElements()) {
			ze = (ZipEntry) zList.nextElement();
			if (ze.isDirectory()) {
				// log.info("打开zip文件里的文件夹:"+ ze.getName() +"skipped...");
				continue;
			}
			OutputStream outputStream = null;
			InputStream inputStream = null;
			try {
				// 以ZipEntry为参数得到一个InputStream,并写到OutputStream中
				outputStream = new BufferedOutputStream(new FileOutputStream(getRealFileName(toDisk, ze.getName())));
				inputStream = new BufferedInputStream(zfile.getInputStream(ze));
				int readLen = 0;
				while ((readLen = inputStream.read(buf, 0, 1024)) != -1) {
					outputStream.write(buf, 0, readLen);
				}
				inputStream.close();
				outputStream.close();
			} catch (Exception e) {
				// log.info("解压失败:"+e.toString());
				throw new IOException("解压失败:" + e.toString());
			} finally {
				if (inputStream != null) {
					try {
						inputStream.close();
					} catch (IOException ex) {

					}
				}
				if (outputStream != null) {
					try {
						outputStream.close();
					} catch (IOException ex) {
						ex.printStackTrace();
					}
				}
				inputStream = null;
				outputStream = null;
			
				
			}

		}
		zfile.close();
	}

    /**
     * 
     * 给定根目录,返回一个相对路径所对应的实际文件名.
     * 
     * @param zippath
     *            指定根目录
     * 
     * @param absFileName
     *            相对路径名,来自于ZipEntry中的name
     * 
     * @return java.io.File 实际的文件
     * 
     */

    private static File getRealFileName(String zippath, String absFileName) {
        // log.info("文件名:"+absFileName);
        String[] dirs = absFileName.split("/", absFileName.length());
        File ret = new File(zippath);// 创建文件对象
        if (dirs.length > 1) {
            for (int i = 0; i < dirs.length - 1; i++) {
                ret = new File(ret, dirs[i]);
            }
        }
        if (!ret.exists()) {// 检测文件是否存在
            ret.mkdirs();// 创建此抽象路径名指定的目录
        }
        ret = new File(ret, dirs[dirs.length - 1]);// 根据 ret 抽象路径名和 child
                                                    // 路径名字符串创建一个新 File 实例
        return ret;
    }
    

    
    
}

文件递归删除工具类(file.delete方法必须文件为空才能删除,所以用这个递归方法删)

   /**
     * 递归删除目录下的所有文件及子目录下所有文件
     * @param dir 将要删除的文件目录
     */
    private static boolean deleteDir(File dir) {
        if (dir.isDirectory()) {
            String[] children = dir.list();
            for (int i=0; i<children.length; i++) {	
                boolean success = deleteDir(new File(dir, children[i]));
                if (!success) {
                    return false;
                }
            }
        }
        // 目录此时为空,可以删除
        return dir.delete(); 
    }

判断zip压缩包是否有文件夹思路

eg:所内 所外俩个文件夹

	/**
	 * 判断是否存在所内所外俩个文件夹
	 * @param oriName
	 * @param savePath
	 * @return
	 * @throws Exception
	 */
	private boolean hasFileDirectory(String oriName, String savePath) throws Exception {
		  ZipFile zfile = new ZipFile(oriName, "gbk");// 连接待解压文件 "utf-8"会乱码
	        Enumeration zList = zfile.getEntries();// 得到zip包里的所	有元素
	        ZipEntry ze = null;
	        int count = 0;
	        while (zList.hasMoreElements()) {
	            ze = (ZipEntry) zList.nextElement();
	            if (ze.isDirectory()) {
	            	if(ze.getName().equals("所内/")) {
	            		count+=1;
	            	}
	            	if(ze.getName().equals("所外/")) {
	            		count+=1;
	            	}
	            }
	                // log.info("打开zip文件里的文件夹:"+ ze.getName() +"skipped...");	      
	         }
	        if(count==2) {
	        	return true;
	        }
		return false;
	}



版权声明:本文为qq_17025903原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。