首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 软件管理 > 软件架构设计 >

java实现先压缩再上载然后删除压缩的文件

2012-10-28 
java实现先压缩再下载然后删除压缩的文件(1):压缩:File zipFile new File(zipfile)用java中的java.util

java实现先压缩再下载然后删除压缩的文件

(1):压缩:

File zipFile = new File(zipfile);

用java中的java.util.zip.ZipOutputStream和java.util.zip.ZipEntry完成压缩功能。

? try {
?? //创建文件输入流对象
?? FileInputStream fis = new FileInputStream(file);
?? //创建文件输出流对象
?? FileOutputStream fos = new FileOutputStream(zipFile);
?? //创建ZIP数据输出流对象
?? ZipOutputStream zos = new ZipOutputStream(fos);//压缩包
?? //创建指向压缩原始文件的入口
?? ZipEntry ze = new ZipEntry(file);
?? zos.putNextEntry(ze);
?? //向压缩文件中输出数据
?? int len;
?? byte[] buf = new byte[2048];
?? while((len=fis.read(buf)) != -1) {
?????????? zos.write(buf,0,len);
?????????? zos.flush();
????? }
????? fis.close();
????? zos.close();
? } catch (IOException e) {
?? System.out.println(e);
? }

?

(2) 下载:

用文件流的形式可以实现:

包括两种形式:一种是通过URL的形式,另一种形式通过response设置相应文本类型,设置输出形式

??????? int len = 0;
??????? response.reset(); // 非常重要
??????? if (isOnline) { // 在线打开方式
??????????? URL u = new URL("file:///" + logsPath+"\"+downloadFileName);
??????????? response.setContentType(u.openConnection().getContentType());
??????????? response.setHeader("Content-Disposition", "inline; filename=" + zipFile.getName());
??????????? //文件名应该编码成UTF-8
??????? } else {//纯下载方式
??????????? response.setContentType("application/x-msdownload");
??????????? response.setHeader("Content-Disposition", "attachment; filename=" + zipFile.getName());
??????? }
???????
?????? BufferedInputStream br = new BufferedInputStream(new FileInputStream(zipFile));
??????? OutputStream out = response.getOutputStream();
??????? byte[] buf = new byte[1024];
??????? while ((len = br.read(buf)) > 0)
??????????? out.write(buf, 0, len);
??????? br.close();
??????? out.close();

(3) 删除就一句话:zipFile.delete();

?

?

1 楼 guoguo1010 2011-08-16   如果是直接下载文件呢
用一般的文件读写怎么不可以
望指教 2 楼 guoguo1010 2011-08-16   错了 是直接下载压缩文件··

热点排行