java下载打包下载文件 - 代码9527

like9527 2021-08-07 原文


java下载打包下载文件


一:对于文件的一些操作

1.创建文件夹

private String CreateFile(String dir) {
File file = new File(dir);
if (!file.exists()) {
//创建文件夹
boolean mkdir = file.mkdir();

} else {

}
return dir;
}

2.复制文件

private void copyFile(File source, File dest) throws IOException {
FileChannel inputChannel = null;
FileChannel outputChannel = null;
try {
inputChannel = new FileInputStream(source).getChannel();
outputChannel = new FileOutputStream(dest).getChannel();
outputChannel.transferFrom(inputChannel, 0, inputChannel.size());
} finally {
inputChannel.close();
outputChannel.close();
}
}

3.删除文件
private void delFile(File file) {
File[] listFiles = file.listFiles();
if (listFiles != null) {
for (File f : listFiles) {
if (f.isDirectory()) {
delFile(f);
} else {
f.delete();
}
}
}
file.delete();
}

 

二:controller的文件下载操作

 

OutputStream out = response.getOutputStream();
byte[] data = FileToZipUtils.createZip(pdir);//这里根据项目里实际的地址去写  ,FileToZipUtils是一个工具类
response.reset();
//response.setHeader(“Content-Disposition”,”attachment;fileName=file.zip”);
response.setHeader(“Content-Disposition”, “attachment; filename=” + java.net.URLEncoder.encode(pname+”.zip”, “UTF-8”));
response.addHeader(“Content-Length”, “”+data.length);
response.setContentType(“application/octet-stream;charset=UTF-8”);
IOUtils.write(data, out);
out.flush();
out.close();

 

三:FileToZipUtils工具类

public class FileToZipUtils {

// 日志
private static Logger log = LoggerFactory.getLogger(FileToZipUtils.class);

/***
* 压缩文件变成zip输出流
*/
public static byte[] createZip(String srcSource) throws Exception{
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
ZipOutputStream zip = new ZipOutputStream(outputStream);
//将目标文件打包成zip导出
File file = new File(srcSource);
createAllFile(zip, file, “”);
IOUtils.closeQuietly(zip);
return outputStream.toByteArray();
}

/***
* 对文件下的文件处理
*/
public static void createAllFile(ZipOutputStream zip, File file, String dir) throws Exception {
//如果当前的是文件夹,则进行进一步处理
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++) {
createAllFile(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);
zip.flush();
zip.closeEntry();
}
}

/**
* 将存放在sourceFilePath目录下的源文件,打包成fileName名称的zip文件,并存放到zipFilePath路径下
*
* @param sourceFilePath
* :待压缩的文件路径
* @param zipFilePath
* :压缩后存放路径
* @param fileName
* :压缩后文件的名称
* @return
*/
public static boolean fileToZip(String sourceFilePath, String zipFilePath, String fileName) {
boolean flag = false;
File sourceFile = new File(sourceFilePath);
FileInputStream fis = null;
BufferedInputStream bis = null;
FileOutputStream fos = null;
ZipOutputStream zos = null;

if (sourceFile.exists() == false) {
log.info(“待压缩的文件目录:” + sourceFilePath + “不存在.”);
} else {
try {
File zipFile = new File(zipFilePath + “/” + fileName + “.zip”);
if (zipFile.exists()) {
log.info(zipFilePath + “目录下存在名字为:” + fileName + “.zip” + “打包文件.”);
} else {
File[] sourceFiles = sourceFile.listFiles();
if (null == sourceFiles || sourceFiles.length < 1) {
log.info(“待压缩的文件目录:” + sourceFilePath + “里面不存在文件,无需压缩.”);
} else {
fos = new FileOutputStream(zipFile);
zos = new ZipOutputStream(new BufferedOutputStream(fos));
byte[] bufs = new byte[1024 * 10];
for (int i = 0; i < sourceFiles.length; i++) {
// 创建ZIP实体,并添加进压缩包
ZipEntry zipEntry = new ZipEntry(sourceFiles[i].getName());
zos.putNextEntry(zipEntry);
// 读取待压缩的文件并写进压缩包里
fis = new FileInputStream(sourceFiles[i]);
bis = new BufferedInputStream(fis, 1024 * 10);
int read = 0;
while ((read = bis.read(bufs, 0, 1024 * 10)) != -1) {
zos.write(bufs, 0, read);
}
}
flag = true;
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
throw new RuntimeException(e);
} catch (IOException e) {
e.printStackTrace();
throw new RuntimeException(e);
} finally {
// 关闭流
try {
if (null != bis)
bis.close();
if (null != zos)
zos.close();
} catch (IOException e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
}
return flag;
}
/**
* 解压缩zip包
*
* @param zipFilePath
* 需要解压的zip文件的全路径
* @param unzipFilePath
* 解压后的文件保存的路径
* @param includeZipFileName
* 解压后的文件保存的路径是否包含压缩文件的文件名。true-包含;false-不包含
*/
@SuppressWarnings(“unchecked”)
public static void unzip(String zipFilePath, String unzipFilePath, boolean includeZipFileName) throws Exception {
if (StringUtils.isNotBlank(zipFilePath) || StringUtils.isNotBlank(unzipFilePath)) {
File zipFile = new File(zipFilePath);
// 如果解压后的文件保存路径包含压缩文件的文件名,则追加该文件名到解压路径
if (includeZipFileName) {
String fileName = zipFile.getName();
if (StringUtils.isNotEmpty(fileName)) {
fileName = fileName.substring(0, fileName.lastIndexOf(“.”));
}
unzipFilePath = unzipFilePath + File.separator + fileName;
}
// 创建解压缩文件保存的路径
File unzipFileDir = new File(unzipFilePath);
if (!unzipFileDir.exists() || !unzipFileDir.isDirectory()) {
unzipFileDir.mkdirs();
}

// 开始解压
ZipEntry entry = null;
String entryFilePath = null, entryDirPath = null;
File entryFile = null, entryDir = null;
int index = 0, count = 0, bufferSize = 1024;
byte[] buffer = new byte[bufferSize];
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
ZipFile zip = new ZipFile(zipFile);
Enumeration<ZipEntry> entries = (Enumeration<ZipEntry>) zip.entries();
// 循环对压缩包里的每一个文件进行解压
while (entries.hasMoreElements()) {
entry = entries.nextElement();
// 构建压缩包中一个文件解压后保存的文件全路径
entryFilePath = unzipFilePath + File.separator + entry.getName();
// 构建解压后保存的文件夹路径
index = entryFilePath.lastIndexOf(File.separator);
if (index != -1) {
entryDirPath = entryFilePath.substring(0, index);
} else {
entryDirPath = “”;
}
entryDir = new File(entryDirPath);
// 如果文件夹路径不存在,则创建文件夹
if (!entryDir.exists() || !entryDir.isDirectory()) {
entryDir.mkdirs();
}

// 创建解压文件
entryFile = new File(entryFilePath);
if (entryFile.exists()) {
// 检测文件是否允许删除,如果不允许删除,将会抛出SecurityException
SecurityManager securityManager = new SecurityManager();
securityManager.checkDelete(entryFilePath);
// 删除已存在的目标文件
entryFile.delete();
}

// 写入文件
bos = new BufferedOutputStream(new FileOutputStream(entryFile));
bis = new BufferedInputStream(zip.getInputStream(entry));
while ((count = bis.read(buffer, 0, bufferSize)) != -1) {
bos.write(buffer, 0, count);
}
bos.flush();
bos.close();
}
zip.close();// 切记一定要关闭掉,不然在同一个线程,你想解压到临时路径之后,再去删除掉这些临时数据,那么就删除不了
}

}
}

posted on
2019-12-26 16:53 
代码9527 
阅读(304
评论(0
编辑 
收藏 
举报

 

版权声明:本文为like9527原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://www.cnblogs.com/like9527/p/12103037.html

java下载打包下载文件 - 代码9527的更多相关文章

  1. 微信小程序如何获取和存储openid与php数据互通 – 跳动的汗水

    微信小程序如何获取和存储openid与php数据互通 杂的微信小程序需要调用数据库里面的数据,这样会减轻小程序 […]...

  2. FastMM 定位内存泄露的代码位置 – ╰★张志峰★╮

    FastMM 定位内存泄露的代码位置 开源的FastMM,使用很简单,在工程的第一行引用FastMM4即可(注 […]...

  3. 子网掩码和IP地址计算网络地址和广播地址的换算 – 路大侠

    子网掩码和IP地址计算网络地址和广播地址的换算 子网掩码和IP地址计算网络地址和广播地址的换算     已知  […]...

  4. 扩展名大全 – 非常+++

    扩展名大全 转自:http://www.loveyuki.com/blogview.asp?logID=687 […]...

  5. 第一章 java体系结构介绍 – lidongsheng

    第一章 java体系结构介绍 java技术的核心java虚拟机 1.3 体系结构   java体系结构包括四个 […]...

  6. 为什么我不建议你去外包公司? – zouhui

    为什么我不建议你去外包公司? 2019-11-12 07:32  zouhui  阅读(34638)  评论( […]...

  7. LTE – Model DCI and PDCCH

      This example shows how to model the control region us […]...

  8. RGB颜色表 – widrin

    RGB颜色表 HTML开发,很多地方都要使用颜色,包括字体颜色、背景颜色等,而颜色有两种表达方式(单词表示法和 […]...

随机推荐

  1. nodejs的jwt实现

    JWTJSON Web Token(JSON Web令牌)是一个开放标准(rfc7519),它定义了一种紧凑的、自包含的方式,用于在各方之间以JSON对象安全地传输信息。此信息可以验证和信任,因为它是数字签名的。jwt可以使用秘密〈使...

  2. Amoeba文档地址

    http://docs.hexnova.com/amoeba/...

  3. 试用QQ做为网站入口。

    试用QQ做为网站入口: 在我的资料的我的主页中添加了网址,试用安卓手机qq查看个人资料,看不到主页资料。 在q […]...

  4. 基于VUE实现的h5网页Web出库单入库单打印设计

    经过将近一个月的研发,初步实现了打印单据的自定义设计,样子还有点丑陋,但是功能基本都实现了,实现了以下功能: […]...

  5. 快速删除rbd设备

    有时候需要删除大量的rbd设备,使用rbd rm 删除会很慢,其实可以采用多线程的方法来删除。   列出所有卷 […]...

  6. 顶峰网谈百度关键词排名基本规则

    本文详细阐述了顶峰网(dingnfengnet.com)对百度关键词排名基本规则的研究成果,明确指明了百度关键 […]...

  7. [综合]visio2013安装提示找不到Office.zh_cn\\officeMUI.mis officemui.xml

    在visio2013安装提示找不到Office.zh_cn\officeMUI.mis officemui.x […]...

  8. 数据结构之链表解析

      我们知道,数组作为数据存储结构有一定的缺陷。在无序数组中,搜索时低效的;而在有序数组中,插入效率又很低;不 […]...

展开目录

目录导航