/** * 解壓文件到指定目錄 * 解壓后的文件名,和以前一致 * @param zipFile 待解壓的zip文件 * @param descDir 指定目錄 */ public static void unZipFiles(File zipFile, String descDir) throws IOException { ZipFile zip = new ZipFile(zipFile, Charset.forName("GBK"));//解決中文文件夾亂碼 String name = zip.getName().substring(zip.getName().lastIndexOf('\\')+1, zip.getName().lastIndexOf('.')); File pathFile = new File(descDir+name); if (!pathFile.exists()) { pathFile.mkdirs(); } for (Enumeration<? extends ZipEntry> entries = zip.entries(); entries.hasMoreElements();) { ZipEntry entry = (ZipEntry) entries.nextElement(); String zipEntryName = entry.getName(); InputStream in = zip.getInputStream(entry); //輸出的目錄 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); FileOutputStream out = new FileOutputStream(outPath); byte[] buf1 = new byte[1024]; int len; while ((len = in.read(buf1)) > 0) { out.write(buf1, 0, len); } in.close(); out.close(); } return; }
/** * multipartFile轉為file * @param multipartFile * @return */ private static File transferToFile(MultipartFile multipartFile) { // 選擇用緩沖區來實現這個轉換即使用java 創建的臨時文件 使用 MultipartFile.transferto()方法 。 File file = null; try { String originalFilename = multipartFile.getOriginalFilename(); String[] filename = originalFilename.split("\\."); file=File.createTempFile(filename[0], filename[1]); multipartFile.transferTo(file); file.deleteOnExit(); } catch (IOException e) { e.printStackTrace(); } return file; }