Java如何導(dǎo)出zip壓縮文件
Java導(dǎo)出zip壓縮文件
這里需要說明的是我的項(xiàng)目需要各種不同文件導(dǎo)出,所以進(jìn)行壓縮,當(dāng)項(xiàng)目上線的時(shí)候,我們是沒有本地電腦路徑的,所以壓縮路徑我選擇在項(xiàng)目的根目錄下,全部壓縮成功,調(diào)用刪除,在進(jìn)行刪除,這樣在虛擬機(jī)上也可以進(jìn)行操作,不會(huì)影響,個(gè)別注意,在linux上很多項(xiàng)目如果不配置中文環(huán)境,導(dǎo)出的文件名會(huì)亂碼,強(qiáng)調(diào)一下,好了,看代碼
/**
* 附件導(dǎo)出 (導(dǎo)出所有用戶上傳的文件格式 已壓縮包形式導(dǎo)出 )。
* 1.創(chuàng)建一個(gè)臨時(shí)存放文件的tempFile。
* 2.在臨時(shí)文件夾中創(chuàng)建用戶文件夾用來存放下載好的文件(用戶文件夾可以用時(shí)間戳或者uuid來命名)。
* 3.把臨時(shí)文件夾壓縮成zip文件,存放到tempfile下面。
* 4.根據(jù)流的形式把壓縮文件讀到放到瀏覽器下載 5.關(guān)閉流,刪除臨時(shí)文件中的用戶文件夾和壓縮好的用戶文件夾。
*
* @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;
// 獲取項(xiàng)目路徑
String rootPath = this.getClass().getClassLoader().getResource("").getPath();
// 創(chuàng)建臨時(shí)文件夾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) {
// 文件夾名稱 根據(jù)序號(hào)名字創(chuàng)建
String id = map.get("id").toString();
String newFile = file1.getPath() + "/" + "序號(hào)" + 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;
// 調(diào)用下載工具類
ZipFileDownload.dolFile(value, path,newFileNmae);
}
}
}
// 調(diào)用方法打包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 {
// 壓縮成功后刪除項(xiàng)目中文件夾
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);
// 將目標(biāo)文件打包成zip導(dǎo)出
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 {
// 如果當(dāng)前的是文件夾,則進(jìn)行進(jìn)一步處理
try {
if (file.isDirectory()) {
// 得到文件列表信息
File[] files = file.listFiles();
// 將文件夾添加到下一級(jí)打包目錄
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 {
// 當(dāng)前的是文件,打包處理文件輸入流
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();
}
}
}
}刪除文件方法:
? ?/**
? ? ?* 刪除文件夾以及文件夾內(nèi)容
? ? ?*?
? ? ?* @param folderPath
? ? ?*/
? ? public static void delFolder(String folderPath) {
? ? ? ? try {
? ? ? ? ? ? delAllFile(folderPath); // 刪除完里面所有內(nèi)容
? ? ? ? ? ? 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并導(dǎo)出
有一個(gè)項(xiàng)目需要將文件夾里面的所有文件壓縮成zip并導(dǎo)出下載,并且保留原來文件夾里面的所有目錄結(jié)構(gòu),找了一些資料整理了一下。
上代碼:
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導(dǎo)出
? ? ?* @param response HttpServletResponse
? ? ?* @param sourceFilePath 需要打包的文件夾路徑
? ? ?* @param fileName 下載時(shí)的文件名稱
? ? ?* @param postfix 下載時(shí)的文件后綴 .zip/.rar
? ? ?*/
? ? public static void exportZip(HttpServletResponse response, String sourceFilePath, String fileName, String postfix) {
? ? ? ? // 默認(rèn)文件名以時(shí)間戳作為前綴
? ? ? ? if(StringUtils.isBlank(fileName)){
? ? ? ? ? ? SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
? ? ? ? ? ? fileName = sdf.format(new Date());
? ? ? ? }
? ? ? ? String downloadName = fileName + postfix;
? ? ? ? // 將文件進(jìn)行打包下載
? ? ? ? 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);
? ? ? ? // 將目標(biāo)文件打包成zip導(dǎo)出
? ? ? ? File file = new File(sourceFilePath);
? ? ? ? handlerFile(zip, file,"");
? ? ? ? // 無異常關(guān)閉流,它將無條件的關(guān)閉一個(gè)可被關(guān)閉的對(duì)象而不拋出任何異常。
? ? ? ? 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 {
? ? ? ? // 如果當(dāng)前的是文件夾,則循環(huán)里面的內(nèi)容繼續(xù)處理
? ? ? ? if (file.isDirectory()) {
? ? ? ? ? ? //得到文件列表信息
? ? ? ? ? ? File[] fileArray = file.listFiles();
? ? ? ? ? ? if (fileArray == null) {
? ? ? ? ? ? ? ? return;
? ? ? ? ? ? }
? ? ? ? ? ? //將文件夾添加到下一級(jí)打包目錄
? ? ? ? ? ? zip.putNextEntry(new ZipEntry(dir + "/"));
? ? ? ? ? ? dir = dir.length() == 0 ? "" : dir + "/";
? ? ? ? ? ? // 遞歸將文件夾中的文件打包
? ? ? ? ? ? for (File f : fileArray) {
? ? ? ? ? ? ? ? handlerFile(zip, f, dir + f.getName());
? ? ? ? ? ? }
? ? ? ? } else {
? ? ? ? ? ? // 如果當(dāng)前的是文件,打包處理
? ? ? ? ? ? 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();
? ? ? ? }
? ? }
}調(diào)用方法:
/**
? ? ?* 導(dǎo)出
? ? ?*/
? ? @GetMapping("/export")
? ? public void getExport(HttpServletResponse response) throws Exception {
? ? ? ? FileZipUtil.exportZip(response, "D:\\Java\\123\\", "違法建筑治理應(yīng)用場(chǎng)景數(shù)據(jù)采集", "zip");
? ? }需要用到的common-io的jar包:
<dependency> ? ?<groupId>org.apache.commons</groupId> ? ? <artifactId>commons-io</artifactId> ? ? <version>1.3.2</version> </dependency>
總結(jié)
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
Java8新特性之空指針異常的克星Optional類的實(shí)現(xiàn)
這篇文章主要介紹了Java8新特性之空指針異常的克星Optional類的實(shí)現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-10-10
Java實(shí)現(xiàn)簡(jiǎn)單QQ聊天工具
這篇文章主要為大家詳細(xì)介紹了Java實(shí)現(xiàn)簡(jiǎn)單QQ聊天工具,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2022-09-09
Spark學(xué)習(xí)筆記 (二)Spark2.3 HA集群的分布式安裝圖文詳解
這篇文章主要介紹了Spark2.3 HA集群的分布式安裝,結(jié)合圖文與實(shí)例形式詳細(xì)分析了Spark2.3 HA集群分布式安裝具體下載、安裝、配置、啟動(dòng)及執(zhí)行spark程序等相關(guān)操作技巧,需要的朋友可以參考下2020-02-02
spring boot 中設(shè)置默認(rèn)網(wǎng)頁(yè)的方法
這篇文章主要介紹了spring boot 中設(shè)置默認(rèn)網(wǎng)頁(yè)的方法,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2018-04-04
java中map和對(duì)象互轉(zhuǎn)工具類的實(shí)現(xiàn)示例
這篇文章主要介紹了java中map和對(duì)象互轉(zhuǎn)工具類的實(shí)現(xiàn)示例,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-08-08

