Java如何导出zip压缩文件
作者:郭优秀的笔记
这篇文章主要介绍了Java如何导出zip压缩文件问题,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
Java导出zip压缩文件
这里需要说明的是我的项目需要各种不同文件导出,所以进行压缩,当项目上线的时候,我们是没有本地电脑路径的,所以压缩路径我选择在项目的根目录下,全部压缩成功,调用删除,在进行删除,这样在虚拟机上也可以进行操作,不会影响,个别注意,在linux上很多项目如果不配置中文环境,导出的文件名会乱码,强调一下,好了,看代码
/**
* 附件导出 (导出所有用户上传的文件格式 已压缩包形式导出 )。
* 1.创建一个临时存放文件的tempFile。
* 2.在临时文件夹中创建用户文件夹用来存放下载好的文件(用户文件夹可以用时间戳或者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();
// 创建临时文件夹tempFile
File tempFile = new File(rootPath + "/tempFile");
if (!tempFile.exists()) {
tempFile.mkdirs();
}
// 创建用户文件夹 用来存放文件
file1 = new File(tempFile.getPath() + "/" + System.currentTimeMillis());
file1.mkdirs();
for (Map<String, Object> map : fromDataList) {
// 文件夹名称 根据序号名字创建
String id = map.get("id").toString();
String newFile = file1.getPath() + "/" + "序号" + id;
// 新建的文件名称和路径
file = new File(newFile);
// 获取文件夹路径
Path path = file.toPath();
// 创建文件夹
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 + "/";
// 循环将文件夹中的文件打包
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();
// 接收压缩包字节
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();
}
}
/**
* 创建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 {
// 如果当前的是文件夹,则循环里面的内容继续处理
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\\", "违法建筑治理应用场景数据采集", "zip");
}需要用到的common-io的jar包:
<dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-io</artifactId> <version>1.3.2</version> </dependency>
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。
