java多多文件打包下载_java代码实现打包多个文件下载功能

/**

* 把接受的全部文件打成压缩包

* @param List;

* @param org.apache.tools.zip.ZipOutputStream

*/

public static void zipFile

(List files,ZipOutputStream outputStream) {

int size = files.size();

for(int i = 0; i < size; i++) {

File file = (File) files.get(i);

zipFile(file, outputStream);

}

}

public static HttpServletResponse downloadZip(File file,HttpServletResponse response) {

try {

// 以流的形式下载文件。

InputStream fis = new BufferedInputStream(new FileInputStream(file.getPath()));

byte[] buffer = new byte[fis.available()];

fis.read(buffer);

fis.close();

// 清空response

response.reset();

OutputStream toClient = new BufferedOutputStream(response.getOutputStream());

response.setContentType("application/octet-stream");

response.setHeader("Content-Disposition", "attachment;filename=" + file.getName());

toClient.write(buffer);

toClient.flush();

toClient.close();

} catch (IOException ex) {

ex.printStackTrace();

}finally{

try {

File f = new File(file.getPath());

f.delete();

} catch (Exception e) {

e.printStackTrace();

}

}

return response;

}

/**

* 根据输入的文件与输出流对文件进行打包

* @param File

* @param org.apache.tools.zip.ZipOutputStream

*/

public static void zipFile(File inputFile,

ZipOutputStream ouputStream) {

try {

if(inputFile.exists()) {

/**如果是目录的话这里是不采取操作的,

* 至于目录的打包正在研究中*/

if (inputFile.isFile()) {

FileInputStream IN = new FileInputStream(inputFile);

BufferedInputStream bins = new BufferedInputStream(IN, 512);

//org.apache.tools.zip.ZipEntry

ZipEntry entry = new ZipEntry(inputFile.getName());

ouputStream.putNextEntry(entry);

// 向压缩文件中输出数据

int nNumber;

byte[] buffer = new byte[512];

while ((nNumber = bins.read(buffer)) != -1) {

ouputStream.write(buffer, 0, nNumber);

}

// 关闭创建的流对象

bins.close();

IN.close();

} else {

try {

File[] files = inputFile.listFiles();

for (int i = 0; i < files.length; i++) {

zipFile(files[i], ouputStream);

}

} catch (Exception e) {

e.printStackTrace();

}

}

}

} catch (Exception e) {

e.printStackTrace();

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值