java 打包下载文件_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 entries = (Enumeration) 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();// 切记一定要关闭掉,不然在同一个线程,你想解压到临时路径之后,再去删除掉这些临时数据,那么就删除不了

}

}

}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/267066.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

也说读书

记得当年毕业前夕&#xff0c;一位教授说&#xff1a;“希望你们毕业后&#xff0c;能坚持每年读10本书。”当时不以为然&#xff0c;区区十本&#xff0c;岂非小菜&#xff01;毕业后&#xff0c;迫于生计&#xff0c;东奔西走&#xff0c;很难静心读书&#xff0c;偶尔拿起书…

C# 巧用anchor和dock设计复杂界面(控件随着窗体大小的变化而变化)【转】

这个在做winform程序的空间编程的时候遇到过太多次了&#xff0c;自己也想留下点经验&#xff0c;搜索了一下&#xff0c;这篇文章很好很强大了&#xff0c;感谢博主“驴子的菜园”。 程序界面如上 各部分简要说明&#xff1a; 整个窗体上覆盖一个splitcontainer。 splitcontai…

修改java启动参数_如何修改jvm启动参数

用java命令查看。用java -option进行修改参数。还有tomcat&#xff0c;eclipse启动时通过配置文件加载的。详细如下&#xff1a;安装Java开发软件时&#xff0c;默认安装包含两个文件夹&#xff0c;一个JDK(Java开发工具箱)&#xff0c;一个JRE(Java运行环境&#xff0c;内含JV…

非常完善的Log4net详细说明(转)

最可能来源&#xff1a;https://blog.csdn.net/ydm19891101/article/details/50561638 其它转载者&#xff1a;http://www.cnblogs.com/zhangchenliang/p/4546352.html 1、概述 log4net是.Net下一个非常优秀的开源日志记录组件。log4net记录日志的功能非常强大。它可以将日志分…

话说招聘面试

最近公司有一个新项目&#xff0c;是一个软件和硬件结合的项目&#xff0c;具体的就是一个cs软件通过485通信操作硬件的基站&#xff0c;基站上面挂着传感器和其他设备&#xff0c; 当然我只负责软件也就是上位机部分。通过1个月多的时间&#xff0c;每天开会开会调研调研&…

mysql内链接与交叉连接_SQLServer 2008中的交叉连接与内部连接

这里是交叉连接和内部连接的最佳示例。考虑下表表&#xff1a;Teacherx------------------------x| TchrId | TeacherName |x----------|-------------x| T1 | Mary || T2 | Jim |x------------------------x表&#xff1a;Studentx-------------…

获得数据库中表字段的名字.txt

获得数据库中所有数据库的名字&#xff1a;select name From sysdatabases 获得某个数据库中所有表的名字&#xff1a;select name from sysobjects where typeU获得某个表中字段的名字&#xff1a;select name from syscolumns where idobject_id(表名)use masterif exists(S…

java pause_java – 更有效的暂停循环方式

可用的工具是&#xff1a;等待/通知 – 我们都试图摆脱这个古老的系统.信号量 – 一旦你的线程抓住它,你持有它直到释放,所以再次抓住它不会阻止.这意味着您无法在自己的线程中暂停.CyclicBarrier – 每次使用时都必须重新创建.ReadWriteLock – 我的最爱.您可以让任意多个线程…

jmeter java接口_JMeter接口Java开发五步曲

想做jmeter接口二次开发但不知道如何入手&#xff0c;要解决这个问题&#xff0c;我们可以分为5个步骤第一步&#xff1a;了解jmeter处理java请求的流程第二步&#xff1a;通过实现jmeter中的接口JavaSamplerClient编写自定义JAVA接口第三步&#xff1a;打包第四步&#xff1a;…

循环

# l []# for x in range(3,10):# #pass# l.append(x)# print(x,:,l)# print(l)#break/continue(break:终止。continue:继续)#list [1,2,3,4] #遍历# for x in list:# if x 3:# print(x,#*20)# break #终止当前循环# else:# pr…

Redhat ssh服务登录慢

redhat在安装以后每次通过ssh服务登录&#xff0c;要等待几秒才能进入。 只要在sshd_config修改一下以下值就好 vim /etc/ssh/sshd_config UseDNS no service sshd restart 再次用ssh终端登录就快了转载于:https://www.cnblogs.com/passedbylove/p/9070405.html

console程序也有版本和图标

控制台程序的版本和图标创建和编辑 最近项目要做一个能够支持批处理的文件转换工具&#xff0c;根据应用环境的需要&#xff0c;用VC6做了一个基于Console的程序&#xff0c;等程序做完了&#xff0c;突然发现需要给这个程序指定版本&#xff0c;一时还真有些迷糊。从来做控制台…

java面向对象语言_Java到底是不是一种纯面向对象语言?

英文原文&#xff1a;Why Java Is a Purely Object-Oriented Language Or Why NotJava是否确实是 “纯面向对象”&#xff1f;让我们深入到Java的世界&#xff0c;试图来证实它。在我刚开始学习Java的前面几年&#xff0c;我从书本里知道了Java是遵循“面向对象编程范式(Object…

Python--DBUtil

Python--DBUtil包 1 简介 DBUtils是一套Python数据库连接池包&#xff0c;并允许对非线程安全的数据库接口进行线程安全包装。DBUtils来自Webware for Python。 DBUtils提供两种外部接口&#xff1a; PersistentDB &#xff1a;提供线程专用的数据库连接&#xff0c;并自动管理…

java calendar计时器_Java Calendar setTimeInMillis()用法及代码示例

Calendar类中的setTimeInMillis(long mill_sec)方法用于根据传递的long值设置由此Calendar表示的Calendars时间。用法:public void setTimeInMillis(long mill_sec)参数&#xff1a;该方法采用long类型的一个参数mill_sec&#xff0c;表示要设置的给定日期。返回值&#xff1a;…

找出两个字符串数组中的相同元素

public static List<String> getAllSameElement1(String[] strArr1,String[] strArr2) { if(strArr1 null || strArr2 null) { return null; } List<String> strList1 new ArrayList<String>(Arrays.asList(strArr1)); //----------代码段1 List<…

@ConfigurationProperties和@Value不同的使用场景,@Bean添加组件 (6.spring boot配置文件注入)...

接上文 注释掉ConfigurationProperties使用Value注解 /*** <bean class"Person">* <property name"lastName" value"字面量/${key}从环境变量、配置文件中获取值/#{spel}"></property>* <bean/>*/ //Spring底层注解…

sqlite的数据导入 导出

数据导入的来源可以是其他应用程序的输出&#xff0c;也可以是指定的文本文件&#xff0c;这里采用指定的文本文件。 1. 首先&#xff0c;确定导入的数据源&#xff0c;这里是待导入的&#xff0c;按固定格式的文本文件。 2. 然后&#xff0c;依照导入的文件格式&#xff0…

java继承孙子类_Java:类与继承

Java&#xff1a;类与继承对于面向对象的程序设计语言来说&#xff0c;类毫无疑问是其最重要的基础。抽象、封装、继承、多态 这四大特性都离不开类&#xff0c;只有存在类&#xff0c;才能体现面向对象编程的特点&#xff0c;今天我们就来了解一些类与继承的相关知识。首先&am…

linux 下安装JDK

安装配置JDK 下载JDK 因为Elasticsearch需要Java环境&#xff0c;所以需先下载JDK&#xff0c;并配置Java的环境\ 下载地址&#xff1a;http://www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads-2133151.html\ 这里我选择jdk-8u151-linux-x64.tar.gz解压安装…