Java如何導出zip壓縮文件
Java導出zip壓縮文件
這里需要說明的是我的項目需要各種不同文件導出,所以進行壓縮,當項目上線的時候,我們是沒有本地電腦路徑的,所以壓縮路徑我選擇在項目的根目錄下,全部壓縮成功,調用刪除,在進行刪除,這樣在虛擬機上也可以進行操作,不會影響,個別注意,在linux上很多項目如果不配置中文環(huán)境,導出的文件名會亂碼,強調一下,好了,看代碼
/** * 附件導出 (導出所有用戶上傳的文件格式 已壓縮包形式導出 )。 * 1.創(chuàng)建一個臨時存放文件的tempFile。 * 2.在臨時文件夾中創(chuàng)建用戶文件夾用來存放下載好的文件(用戶文件夾可以用時間戳或者uuid來命名)。 * 3.把臨時文件夾壓縮成zip文件,存放到tempfile下面。 * 4.根據流的形式把壓縮文件讀到放到瀏覽器下載 5.關閉流,刪除臨時文件中的用戶文件夾和壓縮好的用戶文件夾。 * * @param response * @param export * @param request * @throws IOException */ @RequestMapping("/fForm/enclosureExport") public void enclosureExport(HttpServletRequest request, HttpServletResponse response) throws IOException { File file1 = null; OutputStream out = response.getOutputStream(); try { Map<String, Object> paramMap = RequestUtils.convertRequestToMap(request); Long formId = getLong(paramMap, "formId"); String condition = getString(paramMap, "condition"); List<Map<String, Object>> fromDataList = fFormService.findFFormData1(formId, condition); File file = null; // 獲取項目路徑 String rootPath = this.getClass().getClassLoader().getResource("").getPath(); // 創(chuàng)建臨時文件夾tempFile File tempFile = new File(rootPath + "/tempFile"); if (!tempFile.exists()) { tempFile.mkdirs(); } // 創(chuàng)建用戶文件夾 用來存放文件 file1 = new File(tempFile.getPath() + "/" + System.currentTimeMillis()); file1.mkdirs(); for (Map<String, Object> map : fromDataList) { // 文件夾名稱 根據序號名字創(chuàng)建 String id = map.get("id").toString(); String newFile = file1.getPath() + "/" + "序號" + id; // 新建的文件名稱和路徑 file = new File(newFile); // 獲取文件夾路徑 Path path = file.toPath(); // 創(chuàng)建文件夾 file.mkdirs(); // 要下載的文件(包含各種文件格式,如圖片 ,視頻,pdf,等等...) Iterator<String> iter = map.keySet().iterator(); while (iter.hasNext()) { String key = iter.next(); String value = map.get(key).toString(); if (value.contains("https://")) { // 截取后綴名 String str = value.substring(value.lastIndexOf(".") + 1); // 截取的文件名 String str1 = value.substring(value.indexOf("com/") + 4, value.indexOf("-baidugongyi")); String newFileNmae = str1 + "." + str; // 調用下載工具類 ZipFileDownload.dolFile(value, path,newFileNmae); } } } // 調用方法打包zip文件 byte[] data = createZip(file1.getPath()); // 壓縮包名稱 String downloadName = file1.getName() + ".zip"; response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(downloadName, "utf-8")); response.addHeader("Content-Length", "" + data.length); response.setContentType("application/octet-stream;charset=UTF-8"); IOUtils.write(data, out); } catch (Exception e) { e.printStackTrace(); } finally { try { // 壓縮成功后刪除項目中文件夾 if (file1.exists()) { FileUtil.delFolder(file1.getPath()); } if (out != null) { out.flush(); out.close(); } } catch (IOException e) { e.printStackTrace(); } } } public byte[] createZip(String srcSource) throws Exception { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); ZipOutputStream zip = new ZipOutputStream(outputStream); // 將目標文件打包成zip導出 File file = new File(srcSource); a(zip, file, ""); IOUtils.closeQuietly(zip); return outputStream.toByteArray(); } public void a(ZipOutputStream zip, File file, String dir) throws Exception { // 如果當前的是文件夾,則進行進一步處理 try { if (file.isDirectory()) { // 得到文件列表信息 File[] files = file.listFiles(); // 將文件夾添加到下一級打包目錄 zip.putNextEntry(new ZipEntry(dir + "/")); dir = dir.length() == 0 ? "" : dir + "/"; // 循環(huán)將文件夾中的文件打包 for (int i = 0; i < files.length; i++) { a(zip, files[i], dir + files[i].getName()); } } else { // 當前的是文件,打包處理文件輸入流 BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file)); ZipEntry entry = new ZipEntry(dir); zip.putNextEntry(entry); zip.write(FileUtils.readFileToByteArray(file)); IOUtils.closeQuietly(bis); } } catch (Exception e) { // TODO: handle exception zip.flush(); zip.close(); } }
文件下載工具類
/** * 文件下載(支持各種文件下載) * @author guoyunlong * */ public class ZipFileDownload { // public static final String HTTp_URL = // "https://gongyi.bj.bcebos.com/Jellyfish-baidugongyi-auction-9f6da244-e87d-4ab9-bd33-bfb9300be5f7.jpg"; // public static void main(String[] args) { // Dol(); // } /** * 文件下載 * * @param urls 需要下載的url * @param path 需要下載的路徑 * @param newFileNmae 截取的新文件名 * @return * @throws IOException */ public static void dolFile(String urls, Path path, String newFileNmae) throws IOException { BufferedInputStream bis = null; BufferedOutputStream bos = null; File file = null; try { if (!urls.equals("") && urls != null) { URL url = new URL(urls); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); // 解決亂碼問題 connection.setRequestProperty("Content-type", "application/x-www-form-urlencoded;charset=UTF-8"); connection.connect(); InputStream is = connection.getInputStream(); bis = new BufferedInputStream(is); file = new File(path + "/" + newFileNmae); FileOutputStream fos = new FileOutputStream(file); bos = new BufferedOutputStream(fos); int b = 0; byte[] byArr = new byte[1024 * 1024]; while ((b = bis.read(byArr)) != -1) { bos.write(byArr, 0, b); } } } catch (Exception e) { e.printStackTrace(); } finally { try { if (bis != null) { bis.close(); } if (bos != null) { bos.flush(); bos.close(); } } catch (IOException e) { e.printStackTrace(); } } } }
刪除文件方法:
? ?/** ? ? ?* 刪除文件夾以及文件夾內容 ? ? ?*? ? ? ?* @param folderPath ? ? ?*/ ? ? public static void delFolder(String folderPath) { ? ? ? ? try { ? ? ? ? ? ? delAllFile(folderPath); // 刪除完里面所有內容 ? ? ? ? ? ? String filePath = folderPath; ? ? ? ? ? ? filePath = filePath.toString(); ? ? ? ? ? ? java.io.File myFilePath = new java.io.File(filePath); ? ? ? ? ? ? myFilePath.delete(); // 刪除空文件夾 ? ? ? ? } catch (Exception e) { ? ? ? ? ? ? e.printStackTrace(); ? ? ? ? } ? ? }
全部代碼就在這里,希望有用
Java將文件夾和里面的所有文件打包成zip或rar并導出
有一個項目需要將文件夾里面的所有文件壓縮成zip并導出下載,并且保留原來文件夾里面的所有目錄結構,找了一些資料整理了一下。
上代碼:
import org.apache.commons.io.FileUtils; import org.apache.commons.io.IOUtils; import javax.servlet.http.HttpServletResponse; import java.io.*; import java.net.URLEncoder; import java.text.SimpleDateFormat; import java.util.Date; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; public class FileZipUtil { ? ? /** ? ? ?* 將指定路徑下的所有文件打包zip導出 ? ? ?* @param response HttpServletResponse ? ? ?* @param sourceFilePath 需要打包的文件夾路徑 ? ? ?* @param fileName 下載時的文件名稱 ? ? ?* @param postfix 下載時的文件后綴 .zip/.rar ? ? ?*/ ? ? public static void exportZip(HttpServletResponse response, String sourceFilePath, String fileName, String postfix) { ? ? ? ? // 默認文件名以時間戳作為前綴 ? ? ? ? if(StringUtils.isBlank(fileName)){ ? ? ? ? ? ? SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss"); ? ? ? ? ? ? fileName = sdf.format(new Date()); ? ? ? ? } ? ? ? ? String downloadName = fileName + postfix; ? ? ? ? // 將文件進行打包下載 ? ? ? ? try { ? ? ? ? ? ? OutputStream os = response.getOutputStream(); ? ? ? ? ? ? // 接收壓縮包字節(jié) ? ? ? ? ? ? byte[] data = createZip(sourceFilePath); ? ? ? ? ? ? response.reset(); ? ? ? ? ? ? response.setCharacterEncoding("UTF-8"); ? ? ? ? ? ? response.addHeader("Access-Control-Allow-Origin", "*"); ? ? ? ? ? ? response.setHeader("Access-Control-Expose-Headers", "*"); ? ? ? ? ? ? // 下載文件名亂碼問題 ? ? ? ? ? ? response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(downloadName, "UTF-8")); ? ? ? ? ? ? //response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + downloadName); ? ? ? ? ? ? response.addHeader("Content-Length", "" + data.length); ? ? ? ? ? ? response.setContentType("application/octet-stream;charset=UTF-8"); ? ? ? ? ? ? IOUtils.write(data, os); ? ? ? ? ? ? os.flush(); ? ? ? ? ? ? os.close(); ? ? ? ? } catch (Exception e) { ? ? ? ? ? ? e.printStackTrace(); ? ? ? ? } ? ? } ? ? /** ? ? ?* 創(chuàng)建zip文件 ? ? ?* @param sourceFilePath ? ? ?* @return byte[] ? ? ?* @throws Exception ? ? ?*/ ? ? private static byte[] createZip(String sourceFilePath) throws Exception{ ? ? ? ? ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); ? ? ? ? ZipOutputStream zip = new ZipOutputStream(outputStream); ? ? ? ? // 將目標文件打包成zip導出 ? ? ? ? File file = new File(sourceFilePath); ? ? ? ? handlerFile(zip, file,""); ? ? ? ? // 無異常關閉流,它將無條件的關閉一個可被關閉的對象而不拋出任何異常。 ? ? ? ? IOUtils.closeQuietly(zip); ? ? ? ? return outputStream.toByteArray(); ? ? } ? ? /** ? ? ?* 打包處理 ? ? ?* @param zip ? ? ?* @param file ? ? ?* @param dir ? ? ?* @throws Exception ? ? ?*/ ? ? private static void handlerFile(ZipOutputStream zip, File file, String dir) throws Exception { ? ? ? ? // 如果當前的是文件夾,則循環(huán)里面的內容繼續(xù)處理 ? ? ? ? if (file.isDirectory()) { ? ? ? ? ? ? //得到文件列表信息 ? ? ? ? ? ? File[] fileArray = file.listFiles(); ? ? ? ? ? ? if (fileArray == null) { ? ? ? ? ? ? ? ? return; ? ? ? ? ? ? } ? ? ? ? ? ? //將文件夾添加到下一級打包目錄 ? ? ? ? ? ? zip.putNextEntry(new ZipEntry(dir + "/")); ? ? ? ? ? ? dir = dir.length() == 0 ? "" : dir + "/"; ? ? ? ? ? ? // 遞歸將文件夾中的文件打包 ? ? ? ? ? ? for (File f : fileArray) { ? ? ? ? ? ? ? ? handlerFile(zip, f, dir + f.getName()); ? ? ? ? ? ? } ? ? ? ? } else { ? ? ? ? ? ? // 如果當前的是文件,打包處理 ? ? ? ? ? ? BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file)); ? ? ? ? ? ? ZipEntry entry = new ZipEntry(dir); ? ? ? ? ? ? zip.putNextEntry(entry); ? ? ? ? ? ? zip.write(FileUtils.readFileToByteArray(file)); ? ? ? ? ? ? IOUtils.closeQuietly(bis); ? ? ? ? ? ? zip.flush(); ? ? ? ? ? ? zip.closeEntry(); ? ? ? ? } ? ? } }
調用方法:
/** ? ? ?* 導出 ? ? ?*/ ? ? @GetMapping("/export") ? ? public void getExport(HttpServletResponse response) throws Exception { ? ? ? ? FileZipUtil.exportZip(response, "D:\\Java\\123\\", "違法建筑治理應用場景數(shù)據采集", "zip"); ? ? }
需要用到的common-io的jar包:
<dependency> ? ?<groupId>org.apache.commons</groupId> ? ? <artifactId>commons-io</artifactId> ? ? <version>1.3.2</version> </dependency>
總結
以上為個人經驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
SpringBoot中實現(xiàn)數(shù)據脫敏處理的方法詳解
項目開發(fā)中,在處理敏感信息時,數(shù)據脫敏是一項重要的安全措施,本文主要為大家介紹了如何在SpringBoot項目中進行數(shù)據脫敏處理,有需要的可以了解下2025-03-03Java高性能本地緩存框架Caffeine的實現(xiàn)
本文主要介紹了Java高性能本地緩存框架Caffeine的實現(xiàn),文中通過示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下2022-02-02Java 實戰(zhàn)范例之線上新聞平臺系統(tǒng)的實現(xiàn)
讀萬卷書不如行萬里路,只學書上的理論是遠遠不夠的,只有在實戰(zhàn)中才能獲得能力的提升,本篇文章手把手帶你用java+jsp+jdbc+mysql實現(xiàn)一個線上新聞平臺系統(tǒng),大家可以在過程中查缺補漏,提升水平2021-11-11Java?深入學習static關鍵字和靜態(tài)屬性及方法
這篇文章主要介紹了Java?深入學習static關鍵字和靜態(tài)屬性及方法,文章通過圍繞主題展開詳細的內容介紹,具有一定的參考價值,需要的小伙伴可以參考一下2022-09-09JAVA基于SnakeYAML實現(xiàn)解析與序列化YAML
這篇文章主要介紹了JAVA基于SnakeYAML實現(xiàn)解析與序列化YAML,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下2019-12-12