压缩包上传 压缩并解压缩Rar/Zip
生活随笔
收集整理的這篇文章主要介紹了
压缩包上传 压缩并解压缩Rar/Zip
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
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");@AutowiredConfig config;@AutowiredMultigrahService multigrahService;@AutowiredBatchService batchService;/*@AutowiredBatchRepo batchRepo*/;/*** 上傳醫(yī)療* * @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")@ResponseBodypublic 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")@ResponseBodypublic 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 {@AutowiredBatchRepo 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");@AutowiredConfig config;@AutowiredUploadRecordsRepo uploadRecordsRepo;@AutowiredUploadRecordsService uploadRecordsService;@AutowiredBatchService 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;}/**** * 轉(zhuǎn)換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 blocke.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 blocke1.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) {// 總數(shù)已超出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")) {// 張數(shù)限制 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) {// 總數(shù)已超出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) {// 總數(shù)已超出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); // 1System.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/imageFullNameno++;}} 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("."));// jsonpathString 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, "票據(jù)有誤", "票據(jù)有誤", type, null, account); 寫入數(shù)據(jù)庫uploadRecordsService.writeUploadRecords(up);} else {delete(imageOldPath);UploadRecords up = new UploadRecords(username, "1",username + "/" + current + "/" + fold + "/" + newimageName, batchId, jsonpath,batchdate, null, "未完成", "未接收", type, null, account); 寫入數(shù)據(jù)庫System.out.println(up.getFinishdate());String imageId = uploadRecordsService.writeUploadRecords(up);if (!imageId.equals("error")) {// 成功上傳System.out.println("成功上傳"); //// System.out.println(base64);String requestXML = "參數(shù)"; // 開始上傳String url = "請求接口";String send = ApiTool.send(requestXML, url);send = send.replaceAll("null", "\"" + jsonpath + "\"");log.info("請求結(jié)果:::" + 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;}/**** * 文件復(fù)制* * @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("文件復(fù)制成功");}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);// 當(dāng)且僅當(dāng)此抽象路徑名表示的文件存在且 是一個目錄時,返回 trueif (!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 + "調(diào)用" + method + "方法時在第" + stackTraceElement.getLineNumber()+ "行代碼處發(fā)生異常!\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("新紀(jì)錄:::" + line);while (line != null) {line = reader.readLine();}reader.close();if (p.waitFor() != 0) {}} catch (IOException e) {e.printStackTrace();} catch (InterruptedException e) {e.printStackTrace();}}/**** * ZIP應(yīng)用* **/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應(yīng)用* **/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;}}?
總結(jié)
以上是生活随笔為你收集整理的压缩包上传 压缩并解压缩Rar/Zip的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 有符号二进制加法溢出判断以及溢出后该如何
- 下一篇: shell if多个条件判断_萌新关于E