Java 解压压缩文件,springMVC 接收压缩文件

解压 zip,rar 类型的压缩文件

1、首先需要 jar 包


ant-1.6.5.jar :解压zip格式的压缩文件

junrar-0.7.jar :解压rar 格式

如果是 maven  :


            ant
            ant
            1.6.5
        
        
            com.github.junrar
            junrar
            0.7
        

加入 springMVC的jar包

2、工具类,

2.1、

网上好多,这里是有2个解压zip 的(一个有编码设置,一个没有编码设置)

2个 解压rar的,(一个有编码设置,一个没有编码设置)

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.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.io.Writer;
import java.util.Enumeration;
import java.util.zip.ZipOutputStream;

import javax.servlet.http.HttpServletRequest;

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

import com.github.junrar.Archive;
import com.github.junrar.rarfile.FileHeader;

public class CompressFileUtils {
	
	public static void unZipFiles(HttpServletRequest request, String zipPath,
			String descDir) throws IOException {
		unZipFiles(request, new File(zipPath), descDir);
	}

	/**
	 * 解压文件到指定目录
	 * 
	 */
	@SuppressWarnings("rawtypes")
	public static void unZipFiles(HttpServletRequest request, File zipFile,
			String descDir) throws IOException {
		request.setCharacterEncoding("utf-8");
		File pathFile = new File(descDir);
		if (!pathFile.exists()) {
			pathFile.mkdirs();
		}
		ZipFile zip = new ZipFile(zipFile);
		for (Enumeration entries = zip.getEntries(); entries.hasMoreElements();) {
			ZipEntry entry = (ZipEntry) entries.nextElement();
			entry.setUnixMode(644); // 解决linux乱码
			String zipEntryName = entry.getName();
			InputStream in = zip.getInputStream(entry);

			BufferedInputStream bis = new BufferedInputStream(in);

			String outPath = (descDir + zipEntryName).replaceAll("\\*", "/");
			;
			// 判断路径是否存在,不存在则创建文件路径
			File file = new File(outPath.substring(0, outPath.lastIndexOf('/')));
			if (!file.exists()) {
				file.mkdirs();
			}
			// 判断文件全路径是否为文件夹,如果是上面已经上传,不需要解压
			if (new File(outPath).isDirectory()) {
				continue;
			}
			// 输出文件路径信息
			System.out.println(outPath);

			OutputStream out = new FileOutputStream(outPath);
			Writer out1 = new OutputStreamWriter(out, "UTF-8");
			byte[] buf1 = new byte[1024];
			int len;
			while ((len = in.read(buf1)) > 0) {
				out.write(buf1, 0, len);
			}
			in.close();
			out.close();
		}
		System.out.println("******************解压完毕********************");
	}

	/**
	 * 根据原始rar路径,解压到指定文件夹下.
	 * 
	 * @param srcRarPath
	 *            原始rar路径
	 * @param dstDirectoryPath
	 *            解压到的文件夹
	 * @throws UnsupportedEncodingException
	 */
	public static void unRarFile(HttpServletRequest request, String srcRarPath,
			String dstDirectoryPath) throws UnsupportedEncodingException {
		request.setCharacterEncoding("utf-8");
		if (!srcRarPath.toLowerCase().endsWith(".rar")) {
			System.out.println("非rar文件!");
			return;
		}
		File dstDiretory = new File(dstDirectoryPath);
		if (!dstDiretory.exists()) {// 目标目录不存在时,创建该文件夹
			dstDiretory.mkdirs();
		}
		Archive a = null;
		try {
			a = new Archive(new File(srcRarPath));
			if (a != null) {
				a.getMainHeader().print(); // 打印文件信息.
				FileHeader fh = a.nextFileHeader();
				while (fh != null) {
					String fileName = fh.getFileNameW().isEmpty()?fh.getFileNameString():fh.getFileNameW();
					System.out.println("fileName"+fileName);
					if (fh.isDirectory()) { // 文件夹
						File fol = new File(dstDirectoryPath + File.separator
								+ fileName);
						fol.mkdirs();
					} else { // 文件
						File out = new File(dstDirectoryPath + File.separator
								+ fh.getFileNameString().trim());
						// System.out.println(out.getAbsolutePath());
						try {// 之所以这么写try,是因为万一这里面有了异常,不影响继续解压.
							
							if (!out.exists()) {
								if (!out.getParentFile().exists()) {// 相对路径可能多级,可能需要创建父目录.
									out.getParentFile().mkdirs();
								}
								out.createNewFile();
							}
							FileOutputStream os = new FileOutputStream(out);
							a.extractFile(fh, os);
							os.close();
						} catch (Exception ex) {
							ex.printStackTrace();
						}
					}
					fh = a.nextFileHeader();
				}
				a.close();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 解压zip文件
	 * 
	 * @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");// 连接待解压文件
		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;
	}
	
	 /** 
     * 根据原始rar路径,解压到指定文件夹下.      
     * @param srcRarPath 原始rar路径 
     * @param dstDirectoryPath 解压到的文件夹      
     */
     public static void unRarFile2(String srcRarPath, String dstDirectoryPath) {
         if (!srcRarPath.toLowerCase().endsWith(".rar")) {
             System.out.println("非rar文件!");
             return;
         }
         System.out.println("dstDirectoryPath"+dstDirectoryPath);
         File dstDiretory = new File(dstDirectoryPath);
         if (!dstDiretory.exists()) {// 目标目录不存在时,创建该文件夹
             dstDiretory.mkdirs();
         }
         Archive a = null;
         try {
             a = new Archive(new File(srcRarPath));
             if (a != null) {
                 //a.getMainHeader().print(); // 打印文件信息.
                 FileHeader fh = a.nextFileHeader();
                 while (fh != null) {
                          //防止文件名中文乱码问题的处理
                
String fileName = fh.getFileNameW().isEmpty()?fh.getFileNameString():fh.getFileNameW();
                     if (fh.isDirectory()) { // 文件夹 
                    File fol = new File(dstDirectoryPath + File.separator + fileName);
                       //  fol.mkdirs();
                     } else { // 文件
                    File out = new File(dstDirectoryPath + File.separator + fileName.trim());
                         try { 
                             if (!out.exists()) {
                                 if (!out.getParentFile().exists()) {// 相对路径可能多级,可能需要创建父目录. 
                                     out.getParentFile().mkdirs();
                                 }
                                 out.createNewFile();
                             }
                             FileOutputStream os = new FileOutputStream(out);
                             a.extractFile(fh, os);
                             os.close();
                         } catch (Exception ex) {
                             ex.printStackTrace();
                         }
                     }
                     fh = a.nextFileHeader();
                 }
                 a.close();
             }
         } catch (Exception e) {
             e.printStackTrace();
         }
     }
}

2.2、

package com.yogapay.boss.utils;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.HashSet;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.fileupload.disk.DiskFileItem;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;


public class UploadUtil {

	
	public static File[] resolveCompressUploadFile(HttpServletRequest request,
			MultipartFile file, String path) throws Exception {

		request.setCharacterEncoding("utf-8");
		/* 截取后缀名 */
		if (file.isEmpty()) {
			throw new Exception("文件不能为空");
		}
//		String fileName = file.getOriginalFilename();
		System.out.println("sssss"+file.getOriginalFilename());
		String fileName = new String(file.getOriginalFilename());
		System.out.println("fileName"+fileName);
		int pos = fileName.lastIndexOf(".");
		String extName = fileName.substring(pos + 1).toLowerCase();
		// 判断上传文件必须是zip或者是rar否则不允许上传
		if (!extName.equals("zip") && !extName.equals("rar")) {
			throw new Exception("上传文件格式错误,请重新上传");
		}
		// 时间加后缀名保存
		String saveName = "aaas" + "." + extName;
		// 根据服务器的文件保存地址和原文件名创建目录文件全路径
		File pushFile = new File(path + "/" + saveName);
		File descFile = new File(path);
		if (!descFile.exists()) {
			descFile.mkdirs();
		}
		// 解压目的文件
		String descDir = path + "/";
		System.out.println("desc:" + descDir);
		file.transferTo(pushFile);

		// 开始解压zip
		if (extName.equals("zip")) {
			CompressFileUtils.zipToFile(path + "/" + saveName, descDir);
		}else if (extName.equals("rar")) {
			// 开始解压rar
			CompressFileUtils.unRarFile2(pushFile.getAbsolutePath(), descDir);
		}   else {
			throw new Exception("文件格式不正确不能解压");
		}
		// 删除 解压完的压缩文件
		doDeleteEmptyDir(path + "/" + saveName);
		return returnFiles(descDir+"");
	}
	//返回 File[]
	public static File[] returnFiles(String strPath) {
		File dir = new File(strPath);
		File[] files = dir.listFiles(); // 该文件目录下文件全部放入数组
		if (files != null) {
			for (int i = 0; i < files.length; i++) {
				String fileName = files[i].getName();
				File f = new File(strPath + File.separator + fileName);
				System.out.println("文件名称:"+fileName);
				if (f.isDirectory()) {// 如果f是目录
					File[] newfiles = f.listFiles();
					return newfiles;
				}

			}
		}
		return files;
	}

	//删除指定文件
	private static void doDeleteEmptyDir(String dir) {
		boolean success = (new File(dir)).delete();
		if (success) {
			System.out.println("Successfully deleted empty directory: " + dir);
		} else {
			System.out.println("Failed to delete empty directory: " + dir);
		}
	}

	// 删除目录下的所有
	public static boolean deleteDir(File dir) {
        if (dir.isDirectory()) {
            String[] children = dir.list();
            //递归删除目录中的子目录下
            for (int i=0; i

3、controller

public String msave(final ModelMap model,	
			@RequestParam("zip") MultipartFile zip,
			HttpServletRequest request) throws SQLException,
			UnsupportedEncodingException {
					String path = request.getSession().getServletContext()
					.getRealPath("images"+File.separator+"jieya");
// 解压,
					File[] Files = UploadUtil.resolveCompressUploadFile(
							request, zip, path);
					if (UploadUtil.inspectFile(Files)) {
						// 保存,这里是将解压的文件保存到123目录下
						for (File file : Files) {
							System.out.println("file" + file.getName());
							if (!saveFile(file, request,
									"123")) {
								throw new Exception();
							}
						}
						System.out.println("删除文件");
						// 删除临时目录
						UploadUtil.deleteDir(new File(path));
					} else {
						System.out.println("文件类型错误");
						throw new Exception();
					}
}

4、jsp

上传压缩文件:



你可能感兴趣的:(spring,mvc,java,解压压缩文件)