压缩包上传 压缩并解压缩Rar/Zip

1.上传压缩包 

package com.example.demo.controller;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.context.annotation.Scope;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import com.example.demo.data.Config;
import com.example.demo.data.UploadRecords;
import com.example.demo.repo.BatchRepo;
import com.example.demo.service.BatchService;
import com.example.demo.service.MultigrahService;
import com.example.demo.service.UploadRecordsService;
import com.example.demo.util.ApiTool;
import com.example.demo.util.UnZip;

@RestController
@Configurable
@RequestMapping("/mul")
public class MultigraphController {
	private static Logger log = Logger.getLogger(MultigraphController.class);
	private static SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	@Autowired
	Config config;
	@Autowired
	MultigrahService multigrahService;
	@Autowired
	BatchService batchService;
	/*@Autowired
	BatchRepo batchRepo*/;

	/**
	 * 上传医疗
	 * 
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	@SuppressWarnings({ "static-access", "unchecked" })
	@RequestMapping("/discern")
	@Scope("prototype")
	public String recognition(@RequestParam(value = "file") MultipartFile file,
			@RequestParam(value = "username") String username, @RequestParam(value = "type") String type,
			@RequestParam(value = "account") String account, HttpServletRequest req) throws IOException {
		Map<String, String> returnmap =multigrahService.recognition(file, username, type, account, req);
		return returnmap.get("info");

	}

	@CrossOrigin
	@RequestMapping("/validate")
	@ResponseBody
	public String validate(@RequestParam(value = "file") MultipartFile file,
			@RequestParam(value = "username") String username, @RequestParam(value = "type") String type,
			@RequestParam(value = "account") String account, HttpServletRequest req, HttpSession session)
					throws Exception {
		log.info("开始验证校验压缩包");
		return multigrahService.validate(file,
				config.getHome() + "image" + File.separator + session.getAttribute("usr"), username);
	}
	@RequestMapping("/selectzip")
	@ResponseBody
	public String selectzipname(@RequestParam(value = "batch_id") String batch_id,HttpServletRequest req) {
		String  name=batchService.selectBatchname(batch_id);
		System.out.println(name);
		return name;
	}
}

 2.录入批次

package com.example.demo.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.example.demo.data.domain.Batch;
import com.example.demo.repo.BatchRepo;
@Service
public class BatchService {
	@Autowired
	BatchRepo  batchRepo;
	public   String  saveBatch(String  name,int count,String date){
		Batch  batch=Batch.builder().name(name).count(count).startdate(date).build();
		batch=batchRepo.save(batch);
		if (batch.getId() != null && batch.getId() > 0){
			return  batch.getId().toString();
		}
		return  "error";
		
	}
	public  String selectBatchname(String batch_id){
		return  batchRepo.selectBatchname(batch_id);
		
	}
	
}

3.验证并上传 

package com.example.demo.service;

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.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.io.FileUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import com.example.demo.controller.Timer;
import com.example.demo.data.Config;
import com.example.demo.data.UploadRecords;
import com.example.demo.repo.UploadRecordsRepo;
import com.example.demo.util.ApiTool;
import com.example.demo.util.Library;
import com.example.demo.util.UnZip;
import com.sun.jna.Memory;
import com.sun.jna.ptr.FloatByReference;
import com.sun.org.apache.xerces.internal.impl.dv.util.Base64;

@Service
public class MultigrahService {
	private static Logger log = Logger.getLogger(MultigrahService.class);
	private static SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	@Autowired
	Config config;
	@Autowired
	UploadRecordsRepo uploadRecordsRepo;
	@Autowired
	UploadRecordsService uploadRecordsService;
	@Autowired
	BatchService batchService;

	public static String generate(String usr) {
		String string = usr + "_";
		for (int i = 0; i < 16; i++) {
			string = string + (int) (Math.random() * 10);
		}
		return string;
	}

	/***
	 * 
	 * 转换base64
	 * 
	 * @param multipartFile
	 * @param imageUrl
	 * @return
	 * @throws Exception
	 */
	@SuppressWarnings("resource")
	public String changeBase64(String oldpath, String newpath, HttpServletRequest req) {
		try {
			InputStream is = new FileInputStream(oldpath);
			int available = is.available();
			byte[] bytes = new byte[available];
			File files = new File(newpath);
			if (!files.exists()) {
				try {
					files.getParentFile().mkdirs();
					files.createNewFile();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
					return "报错:" + e.getMessage() + "," + e.toString() + "," + ErrorToLogString(e) + ",files=" + files
							+ "req:" + req + "path:" + newpath;
				}

			}
			FileOutputStream fileOutputStream = new FileOutputStream(files);
			is.read(bytes);
			fileOutputStream.write(bytes);
			fileOutputStream.close();
			delete(oldpath);
			is.close();
			String base64 = Base64.encode(bytes);
			base64 = base64.replace("+", "%2B");
			return base64;
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		return "error";

	}

	/***
	 * 
	 * 要求验证
	 * 
	 * @param multipartFile
	 * @param imageUrl
	 * @return
	 * @throws Exception
	 */
	@SuppressWarnings("unchecked")
	public String validate(MultipartFile multipartFile, String imageUrl, String username) throws Exception {
		if (username == null || username.equals("")) {
			return "login";
		}
		String originalFilename = multipartFile.getOriginalFilename();
		long size = multipartFile.getSize();
		InputStream inputStream = multipartFile.getInputStream();
		imageUrl = imageUrl + "/";
		int upcount = uploadRecordsRepo.selectCount(username) + uploadRecordsRepo.selectBatchCount(username);
		if (upcount >= 30) {// 总数已超出20张
			return "maxCount";
		} else {
			String contentType = originalFilename.substring(originalFilename.lastIndexOf(".") + 1);
			if (!(contentType.toLowerCase()).equals("zip") && !(contentType.toLowerCase()).equals("rar")) {
				return "format";
			} else {
				String fileFullName = Timer.getPinYin(originalFilename);
				SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
				Date date = new Date();
				String current = sdf.format(date);
				String DLL_PATH = config.getHome() + "dll";
				log.info("dll的路径" + DLL_PATH);
				System.setProperty("jna.library.path", DLL_PATH);
				if (!(contentType.toLowerCase()).equals("zip") && !(contentType.toLowerCase()).equals("rar")) {// 没用到
					size = size / 1024 / 1024;

					if (size > 8) {
						return "imageSize";
					} else {

						FileUtils.copyInputStreamToFile(inputStream, new File(imageUrl, fileFullName));
						Memory discription = new Memory(10);
						discription.clear();
						FloatByReference confidence = new FloatByReference();
						String oldFileUrl = imageUrl + fileFullName;
						log.info("源目录:::" + oldFileUrl);
						try {
							Library.eai_qt_detect(oldFileUrl, discription, confidence);
						} catch (Throwable e) {
							log.error("图片" + oldFileUrl + "出错" + e.getMessage());
						}
						String result = discription.getString(0);
						System.out.println(result);
						if (result.equals("blur")) {
							delete(oldFileUrl);
							return "imageBlur";
						} else if (result.equals("curl")) {
							delete(oldFileUrl);
							return "imageCurl";
						} else {
							return "success";
						}
					}
				} else {
					FileUtils.copyInputStreamToFile(inputStream, new File(imageUrl, fileFullName));
					String zipUrl = imageUrl + fileFullName;
					File dir = new File(imageUrl);
					imageUrl = imageUrl + current + "/";
					Map<String, Object> map = new HashMap<String, Object>();
					UnZip.unZip(zipUrl, imageUrl);
					String rootfolder = fileFullName.substring(0, fileFullName.lastIndexOf("."));
					if ((contentType.toLowerCase()).equals("rar")) {
						map = UnZip.zipValidate(zipUrl, contentType, imageUrl + getFileList(imageUrl, rootfolder) + "/",
								getFileList(imageUrl, rootfolder));
					} else {
						map = UnZip.zipValidate(zipUrl, contentType, "", "");
					}
					if (!(Boolean) map.get("count")) {// 张数限制 delete(zipUrl);
						deletefile(imageUrl.substring(0, imageUrl.lastIndexOf("/")));
						delete(zipUrl);
						return "zipCount";
					} else {
						if (!(Boolean) map.get("suffix")) {
							delete(zipUrl);
							deletefile(imageUrl.substring(0, imageUrl.lastIndexOf("/")));
							return "zipSuffix";
						} else {
							if (!(Boolean) map.get("size")) {
								delete(zipUrl);
								deletefile(imageUrl.substring(0, imageUrl.lastIndexOf("/")));
								return "zipSize";
							} else {
								try {
									// UnZip.unZip(zipUrl, imageUrl);
									if ((Boolean) map.get("isDirectory")) {
										String chineseFolder = map.get("folder").toString();
										String folder = Timer.getPinYin(chineseFolder);
										renameTo(imageUrl + chineseFolder, imageUrl + folder);
										List<String> list = (List<String>) map.get("list");
										upcount = upcount + 1;
										log.info("今日已上传了" + upcount + "张");
										if (upcount > 30) {// 总数已超出20张
											delete(zipUrl);
											deletefile(imageUrl.substring(0, imageUrl.lastIndexOf("/")));
											String info = "每天限制30个赔案包,今日已上传了" + (upcount - 1) + "个";
											return info;
										}
										int no = 0;
										for (String chineseString : list) {
											String string = Timer.getPinYin(chineseString);
											String prev = string.substring(0, string.lastIndexOf("."));
											String suf = string.substring(string.lastIndexOf(".") + 1);
											string = prev + no + "." + suf;
											log.info("new name:::" + string);
											renameTo(imageUrl + folder + "/" + chineseString,
													imageUrl + folder + "/" + string);
											no++;
										}
										int no2 = 0;
										for (String string : list) {
											string = Timer.getPinYin(string);
											String prev = string.substring(0, string.lastIndexOf("."));
											String suf = string.substring(string.lastIndexOf(".") + 1);
											string = prev + no2 + "." + suf;
											delete(imageUrl + folder + "/" + string);
											no2++;

										}
										// delete(imageUrl + folder);
										deletefile(imageUrl.substring(0, imageUrl.lastIndexOf("/")));
										return "success";
									} else {
										List<String> list = (List<String>) map.get("list");
										upcount = upcount + 1;
										log.info("今日已上传了" + upcount + "张");
										if (upcount >= 30) {// 总数已超出20张
											delete(zipUrl);
											deletefile(imageUrl.substring(0, imageUrl.lastIndexOf("/")));
											String info = "每天限制30个赔案包,今日已上传了" + (upcount - 1) + "个";
											return info;
										}
										int no = 0;
										for (String chineseString : list) {
											String string = Timer.getPinYin(chineseString);
											String prev = string.substring(0, string.lastIndexOf("."));
											String suf = string.substring(string.lastIndexOf(".") + 1);
											string = prev + no + "." + suf;
											log.info("new name:::" + string);
											System.out.println("返回" + imageUrl + chineseString);
											renameTo(imageUrl + chineseString, imageUrl + string);
											no++;
										}
										int no2 = 0;
										for (String string : list) {
											string = Timer.getPinYin(string);
											String prev = string.substring(0, string.lastIndexOf("."));
											String suf = string.substring(string.lastIndexOf(".") + 1);
											string = prev + no2 + "." + suf;
											delete(imageUrl + string);
											no2++;
										}
										deletefile(imageUrl.substring(0, imageUrl.lastIndexOf("/")));
										return "success";
									}
								} catch (Exception e) {
									delete(zipUrl);
									return "unZip";
								}
							}
						}
					}
				}
			}
		}
	}

	/***
	 * 
	 * 压缩包上传
	 * 
	 * @param multipartFile
	 * @param imageUrl
	 * @return
	 * @throws Exception
	 */
	public Map<String, String> recognition(MultipartFile file, String username, String type, String account,
			HttpServletRequest req) throws IOException {
		Map<String, String> returnmap = new HashMap<String, String>();
		String imageUrl = config.getHome() + "image/" + username + "/";
		String newimageUrl = "";
		String fold = "";
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
		Date date = new Date();
		String current = sdf.format(date);
		if (username == null || username.equals("")) {
			returnmap.put("info", "login");
		}
		String originalFilename = file.getOriginalFilename();
		originalFilename = Timer.getPinYin(originalFilename);
		originalFilename = originalFilename.trim().substring(originalFilename.lastIndexOf("\\") + 1);
		String parentname = originalFilename.substring(0, originalFilename.lastIndexOf("."));// 压缩包前缀
		String contentType = originalFilename.substring(originalFilename.lastIndexOf(".") + 1);// 压缩包后缀
		log.info(parentname + "文件后缀名" + contentType);
		String info = "";
		if (!(contentType.toLowerCase()).equals("zip") && !(contentType.toLowerCase()).equals("rar")) {

		} else {
			String zipUrl = imageUrl + originalFilename;
			int count = 0;
			try {
				File dir = new File(imageUrl);
				imageUrl = imageUrl + current + "/";
				Map<String, Object> map = new HashMap<String, Object>();
				UnZip.unZip(zipUrl, imageUrl); // 1
				System.out.println("解压路径:::" + imageUrl);
				String rootfolder = originalFilename.substring(0, originalFilename.lastIndexOf("."));
				if ((contentType.toLowerCase()).equals("rar")) {
					map = UnZip.zipValidate(zipUrl, contentType, imageUrl + getFileList(imageUrl, rootfolder) + "/",
							getFileList(imageUrl, rootfolder));
				} else {
					map = UnZip.zipValidate(zipUrl, contentType, "", "");
				}
				delete(zipUrl);
				List<String> list = (List<String>) map.get("list");
				List<String> imagenamelist = new ArrayList<String>();
				count = list.size();
				int no = 0;
				if ((Boolean) map.get("isDirectory")) {
					String folder = map.get("folder").toString();
					for (String imageChineseFullName : list) {
						String prev = imageChineseFullName.substring(0, imageChineseFullName.lastIndexOf("."));
						String suf = imageChineseFullName.substring(imageChineseFullName.lastIndexOf(".") + 1);
						String newimageChineseFullName = prev + no + "." + suf;
						renameTo(imageUrl + folder + "/" + imageChineseFullName,
								imageUrl + folder + "/" + newimageChineseFullName);// 重命名
						String imageFullName = Timer.getPinYin(newimageChineseFullName);
						renameTo(imageUrl + folder + "/" + newimageChineseFullName,
								imageUrl + folder + "/" + imageFullName);// 重命名
						newimageUrl = imageUrl + folder + "/";
						fold = folder;
						// wjj folder/imageFullName
						no++;
					}

				} else {
					for (String imageChineseFullName : list) {
						String prev = imageChineseFullName.substring(0, imageChineseFullName.lastIndexOf("."));
						String suf = imageChineseFullName.substring(imageChineseFullName.lastIndexOf(".") + 1);
						String newimageChineseFullName = prev + no + "." + suf;
						System.out.println(newimageChineseFullName);
						renameTo(imageUrl + imageChineseFullName, imageUrl + newimageChineseFullName);// 重命名
						String imageFullName = Timer.getPinYin(newimageChineseFullName);
						newimageUrl = imageUrl + parentname + "/";
						fold = parentname;
						mkdir(newimageUrl);
						renameTo(imageUrl + newimageChineseFullName, newimageUrl + "/" + imageFullName);
						System.out.println(newimageChineseFullName + "---" + newimageUrl);
						no++;
					}
				}
				String batchdate = df.format(new Date());// 图片上传时间
				String batchId = batchService.saveBatch(originalFilename, list.size(), batchdate);// 第一张建模开始时间
				// log.info("新批次号" + batchId);
				int no2 = 0;
				for (String string : list) {
					int id = uploadRecordsService.selectMaxUploadId();
					log.info("新上传号为:::" + id + "----批次号:::" + batchId);
					String prevc = string.substring(0, string.lastIndexOf("."));
					String sufc = string.substring(string.lastIndexOf(".") + 1);
					String newimageChineseFullName = prevc + no2 + "." + sufc;
					System.out.println(newimageChineseFullName);
					String imageFullName = Timer.getPinYin(newimageChineseFullName);
					String imageName = imageFullName.substring(imageFullName.lastIndexOf("\\") + 1);
					String prev = imageName.substring(0, imageName.lastIndexOf("."));// 图片名前缀
					String suf = imageName.substring(imageName.lastIndexOf(".") + 1);// 图片名后缀
					log.info("imageName:::" + imageName + "----图片前缀:::" + prev);
					String newimageName = prev + "_" + batchId + "_" + id + "." + suf;// 文件名
					imagenamelist.add(newimageName);
					String jsonpath = newimageName.substring(0, newimageName.lastIndexOf("."));// jsonpath
					String imageOldPath = newimageUrl + imageName;
					String newimagePath = newimageUrl + newimageName;
					System.out.println("新路径上传" + imageFullName + "---" + imageName + "---" + newimageName);
					String base64 = changeBase64(imageOldPath, newimagePath, req);
					no2++;
					if (base64 == null || base64 == "") {
						info = "其他图上传成功," + imageFullName + "图片有误";
						UploadRecords up = new UploadRecords(username, "1",
								username + "/" + current + "/" + fold + "/" + newimageName, batchId, jsonpath,
								batchdate, null, "票据有误", "票据有误", type, null, account); 写入数据库
						uploadRecordsService.writeUploadRecords(up);
					} else {
						delete(imageOldPath);
						UploadRecords up = new UploadRecords(username, "1",
								username + "/" + current + "/" + fold + "/" + newimageName, batchId, jsonpath,
								batchdate, null, "未完成", "未接收", type, null, account); 写入数据库
						System.out.println(up.getFinishdate());
						String imageId = uploadRecordsService.writeUploadRecords(up);
						if (!imageId.equals("error")) {// 成功上传
							System.out.println("成功上传"); //
							// System.out.println(base64);
							String requestXML = "参数"; // 开始上传
							String url = "请求接口";
							String send = ApiTool.send(requestXML, url);
							send = send.replaceAll("null", "\"" + jsonpath + "\"");
							log.info("请求结果:::" + send);
							if (send.equals("2")) {
								uploadRecordsService.updateUploadRecordsById(null, "接收失败", "未接收", id);
								continue;
							} else {
								uploadRecordsService.updateUploadRecordsById(null, "接收成功", "未接收", id);
								continue;
							}
						}
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
				// return "报错:" + e.getMessage() + "," + e.toString() + "," +
				// ErrorToLogString(e) + "req:" + req;
				returnmap.put("info", "error");
				return returnmap;
			}
			if (info != "") {
				returnmap.put("info", info);
				return returnmap;
			} else {
				returnmap.put("info", String.valueOf(count));
				return returnmap;
			}
		}
		return returnmap;
	}

	/***
	 * 
	 * 文件复制
	 * 
	 * @param multipartFile
	 * @param imageUrl
	 * @return
	 * @throws Exception
	 */
	public static void copyFile(String src, String target) {
		File srcFile = new File(src);
		File targetFile = new File(target);
		try {
			InputStream in = new FileInputStream(srcFile);
			OutputStream out = new FileOutputStream(targetFile);
			byte[] bytes = new byte[1024];
			int len = -1;
			while ((len = in.read(bytes)) != -1) {
				out.write(bytes, 0, len);
			}
			in.close();
			out.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		System.out.println("文件复制成功");

	}

	public static void mkdir(String folderStr) {
		File folderFile = new File(folderStr);
		folderFile.mkdir();
	}

	public static void renameTo(String oldStr, String newStr) {
		File oldFile = new File(oldStr);
		File newFile = new File(newStr);
		oldFile.renameTo(newFile);
	}

	public static void delete(String fileStr) {
		File file = new File(fileStr);
		file.delete();
	}

	/*
	 * 读取指定路径下的文件名和目录名
	 */
	public String getFileList(String rarpath, String rootfolder) {
		File file = new File(rarpath);

		File[] fileList = file.listFiles();
		String fileName = "";
		for (int i = 0; i < fileList.length; i++) {
			if (fileList[i].isFile()) {
				// fileName = fileList[i].getName();
				mkdir(rarpath + rootfolder);
				renameTo(rarpath + fileList[i].getName(), rarpath + rootfolder + "/" + fileList[i].getName());
				fileName = rootfolder;
				System.out.println("文件:" + fileName);
			}

			if (fileList[i].isDirectory()) {
				fileName = fileList[i].getName();
				System.out.println("目录:" + fileName);
			}
		}
		return fileName;
	}

	/**
	 * 删除某个文件夹下的所有文件夹和文件
	 * 
	 * @param delpath
	 *            String
	 * @throws FileNotFoundException
	 * @throws IOException
	 * @return boolean
	 */
	public static boolean deletefile(String delpath) throws Exception {
		try {

			File file = new File(delpath);
			// 当且仅当此抽象路径名表示的文件存在且 是一个目录时,返回 true
			if (!file.isDirectory()) {
				file.delete();
			} else if (file.isDirectory()) {
				String[] filelist = file.list();
				for (int i = 0; i < filelist.length; i++) {
					File delfile = new File(delpath + "\\" + filelist[i]);
					if (!delfile.isDirectory()) {
						delfile.delete();
						System.out.println(delfile.getAbsolutePath() + "删除文件成功");
					} else if (delfile.isDirectory()) {
						deletefile(delpath + "\\" + filelist[i]);
					}
				}
				System.out.println(file.getAbsolutePath() + "删除成功");
				file.delete();
			}

		} catch (FileNotFoundException e) {
			System.out.println("deletefile() Exception:" + e.getMessage());
		}
		return true;
	}

	public static void delAll(String folderStr) {
		File folderFile = new File(folderStr);
		File[] files = folderFile.listFiles();
		if (files != null) {
			for (File file : files) {
				if (!file.isDirectory()) {
					file.delete();
				}
			}
			folderFile.delete();
		}
	}

	private String ErrorToLogString(Exception e) {
		StackTraceElement[] st = e.getStackTrace();
		String errorMessage = "";
		for (StackTraceElement stackTraceElement : st) {
			String exclass = stackTraceElement.getClassName();
			String method = stackTraceElement.getMethodName();
			String message = "类:" + exclass + "调用" + method + "方法时在第" + stackTraceElement.getLineNumber()
					+ "行代码处发生异常!\r\n";
			errorMessage = errorMessage + message;
		}
		if (errorMessage.length() >= 990) {
			errorMessage = errorMessage.substring(0, 990) + "......";
		}
		return errorMessage;
	}
}

4.必须下载WinRar工具并 把cmd路径修改为winrar.exe的路径

package com.example.demo.util;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipInputStream;



public class UnZip {

	public static Map<String, Object> zipValidate(String path, String contentType, String rarurl,String folder) throws Exception {
		Map<String, Object> map = new HashMap<String, Object>();
		if ((contentType.toLowerCase()).equals("zip")) {
			map = traverseFolder0(path, contentType);
		} else if ((contentType.toLowerCase()).equals("rar")) {
			String foldername = folder;
			System.out.println("raruel:::" + rarurl + "目录名:::" + foldername);
			map = traverseFolder1(rarurl, foldername);

		}
		return map;
	}

	/***
	 * 
	 * 解压缩
	 * 
	 **/
	public static void unZip(String zip, String path) throws Exception {
		String[] cmd = { "C:/Program Files/WinRAR/WinRAR.exe", "x", "-y", zip, path };
		Runtime runtime = Runtime.getRuntime();
		try {
			Process p = runtime.exec(cmd);
			System.out.println("---" + p);
			BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream(), "GBK"));
			String line = reader.readLine();
			System.out.println("新纪录:::" + line);
			while (line != null) {
				line = reader.readLine();
			}
			reader.close();
			if (p.waitFor() != 0) {
			}
		} catch (IOException e) {
			e.printStackTrace();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}

	/***
	 * 
	 * ZIP应用
	 * 
	 **/
	public static Map<String, Object> traverseFolder0(String path, String contentType) throws Exception {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("count", true);
		map.put("suffix", true);
		map.put("size", true);
		map.put("isDirectory", false);
		InputStream inputStream = new BufferedInputStream(new FileInputStream(path));
		Charset charset = Charset.forName("GBK");
		ZipInputStream zipInputStream = new ZipInputStream(inputStream, charset);
		java.util.zip.ZipEntry zipEntry;
		int count = 0;
		List<String> list = new LinkedList<String>();
		while ((zipEntry = zipInputStream.getNextEntry()) != null) {
			if (!zipEntry.isDirectory()) {
				count++;
				String name = zipEntry.getName();
				if (name.indexOf("/") != -1) {
					name = name.substring(name.lastIndexOf("/") + 1);
				}
				list.add(name);
				String type = name.substring(name.lastIndexOf(".") + 1);
				if (!type.equals("jpg") && !type.equals("JPG") && !type.equals("png") && !type.equals("PNG")
						&& !type.equals("gif") && !type.equals("GIF") && !type.equals("jpeg") && !type.equals("JPEG")) {
					// System.out.println(name+type);
					map.put("suffix", false);
				}
				long size = zipEntry.getSize();
				size = size / 1024 / 1024;
				if (size > 8) {
					map.put("size", false);
				}
			} else {
				map.put("isDirectory", true);
				String name = zipEntry.getName();
				name = name.substring(0, name.length() - 1);
				map.put("folder", name);
			}
		}
		zipInputStream.close();
		map.put("list", list);
		if (count > 20) {
			map.put("count", false);
		}
		return map;
	}

	/***
	 * 
	 * RAR应用
	 * 
	 **/
	public static Map<String, Object> traverseFolder1(String path, String foldername) {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("count", true);
		map.put("suffix", true);
		map.put("size", true);
		map.put("isDirectory", false);
		int fileNum = 0, folderNum = 0;
		File file = new File(path);
		List<String> list = new LinkedList<String>();
		if (file.exists()) {
			// LinkedList<File> list = new LinkedList<File>();
			File[] files = file.listFiles();
			for (File file2 : files) {
				if (!file2.isDirectory()) {
					System.out.println("1文件夹:" + file2.getAbsolutePath() + "---大小:::"
							+ getTotalSizeOfFilesInDir(new File(file2.getAbsolutePath())));
					long size = getTotalSizeOfFilesInDir(new File(file2.getAbsolutePath()));
					size = size / 1024 / 1024;
					if (size > 8) {
						map.put("size", false);
					}
					String type = file2.getAbsolutePath().substring(file2.getAbsolutePath().lastIndexOf(".") + 1);
					if (!type.equals("jpg") && !type.equals("JPG") && !type.equals("png") && !type.equals("PNG")
							&& !type.equals("gif") && !type.equals("GIF") && !type.equals("jpeg")
							&& !type.equals("JPEG")) {
						// System.out.println(name+type);
						map.put("suffix", false);
					}
					String name = file2.getAbsolutePath();
					System.out.println(name);
					list.add(name.substring(name.lastIndexOf("\\") + 1));
					fileNum++;
				} else {
					System.out.println("1文件:" + file2.getAbsolutePath() + "---大小:::"
							+ getTotalSizeOfFilesInDir(new File(file2.getAbsolutePath())));
					map.put("isDirectory", true);
					String name = file2.getAbsolutePath().substring(file2.getAbsolutePath().lastIndexOf(".") + 1);
					map.put("folder", name);
					list.add(file2.getAbsolutePath());
					folderNum++;
				}

			}
			map.put("isDirectory", true);// rar直接读取
			map.put("folder", foldername);
			map.put("list", list);
		
		} else {
			File filerar = new File(path.replace("/" + foldername + "/", ""));
			if (filerar.exists()) {
				// LinkedList<File> list = new LinkedList<File>();
				File[] files = filerar.listFiles();
				for (File file2 : files) {
					if (!file2.isDirectory()) {
						System.out.println("1文件夹:" + file2.getAbsolutePath() + "---大小:::"
								+ getTotalSizeOfFilesInDir(new File(file2.getAbsolutePath())));
						long size = getTotalSizeOfFilesInDir(new File(file2.getAbsolutePath()));
						size = size / 1024 / 1024;
						if (size > 8) {
							map.put("size", false);
						}
						String type = file2.getAbsolutePath().substring(file2.getAbsolutePath().lastIndexOf(".") + 1);
						if (!type.equals("jpg") && !type.equals("JPG") && !type.equals("png") && !type.equals("PNG")
								&& !type.equals("gif") && !type.equals("GIF") && !type.equals("jpeg")
								&& !type.equals("JPEG")) {
							// System.out.println(name+type);
							map.put("suffix", false);
						}
						String name = file2.getAbsolutePath();
						System.out.println(name);
						list.add(name.substring(name.lastIndexOf("\\") + 1));
						fileNum++;
					}

				}
			}
			map.put("isDirectory", false);
			map.put("folder", foldername);
			map.put("list", list);
			System.out.println("文件不存在!");
		}
		if (fileNum > 20) {
			map.put("count", false);
		}
		System.out.println("文件夹共有:" + folderNum + ",文件共有:" + fileNum);
		return map;

	}

	// 递归方式 计算文件的大小
	private static long getTotalSizeOfFilesInDir(final File file) {
		if (file.isFile())
			return file.length();
		final File[] children = file.listFiles();
		long total = 0;
		if (children != null)
			for (final File child : children)
				total += getTotalSizeOfFilesInDir(child);
		return total;
	}


}

 

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值