Java實現匯出ZIP壓縮包的方法
阿新 • • 發佈:2020-11-03
最近接觸到一個需求要求壓縮匯出檔案,於是乎便要致力於研究一下工具類啦,故也誕生了此篇文章。
下面程式碼中,溪源也將import
匯入的依賴也貼出來了,避免大家引入錯誤。
import org.apache.commons.io.FileUtils; import org.apache.commons.io.IOUtils; import javax.servlet.http.HttpServletResponse; import java.io.*; import java.text.SimpleDateFormat; import java.util.Date; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; /** * @author wx * @date 2020/10/29 5:19 下午 */ public class FileZipUtil { private static void handlerFile(ZipOutputStream zip,File file,String dir) throws Exception { //如果當前的是資料夾,則進行進一步處理 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(); } } 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(); } public static void exportZip(HttpServletResponse response,String sourceFilePath) { //檔名以時間戳作為字首 SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss"); String filePrefix = sdf.format(new Date()); String downloadName = filePrefix + ".zip"; //將檔案進行打包下載 try { OutputStream out = response.getOutputStream(); //接收壓縮包位元組 byte[] data = createZip(sourceFilePath); response.reset(); response.addHeader("Access-Control-Allow-Origin","*"); response.setHeader("Access-Control-Expose-Headers","*"); 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,out); out.flush(); out.close(); } catch (Exception e) { e.printStackTrace(); } } }
客戶端呼叫方法:
@GetMapping("/exportFile") public Result exportFile(HttpServletResponse response) { //第二個引數為:要壓縮檔案的地址 FileZipUtil.exportZip(response,"/Users/Downloads"); }
到此這篇關於Java實現匯出ZIP壓縮包的方法的文章就介紹到這了,更多相關Java匯出ZIP壓縮包內容請搜尋我們以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援我們!