Java打包File
2016-01-14 10:54
351 查看
public static void zipDirectory(String directory, HttpServletResponse response) { File zipfile = new File(directory + ".rar"); File prentfile = new File(directory); File[] files = prentfile.listFiles(); FileOutputStream fous; try { fous = new FileOutputStream(zipfile); ZipOutputStream zipOut = new ZipOutputStream(fous); zipFile(files, zipOut); zipOut.close(); fous.close(); // 下载 InputStream fis = new BufferedInputStream(new FileInputStream(zipfile.getPath())); byte[] buffer = new byte[fis.available()]; fis.read(buffer); fis.close(); // 清空response response.reset(); OutputStream out = new BufferedOutputStream(response.getOutputStream()); response.setContentType("application/octet-stream"); response.setHeader("Content-Disposition", "attachment;filename=" + zipfile.getName()); out.write(buffer); out.flush(); out.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } public static void zipFile(File[] files, ZipOutputStream outputStream) { for (int i = 0; i < files.length; i++) { zipFile(files[i], outputStream); } } 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(); } }
相关文章推荐
- java对世界各个时区(TimeZone)的通用转换处理方法(转载)
- java-注解annotation
- java-模拟tomcat服务器
- java-用HttpURLConnection发送Http请求.
- java-WEB中的监听器Lisener
- Android IPC进程间通讯机制
- Android Native 绘图方法
- Android java 与 javascript互访(相互调用)的方法例子
- 介绍一款信息管理系统的开源框架---jeecg
- 聚类算法之kmeans算法java版本
- java实现 PageRank算法
- PropertyChangeListener简单理解
- c++11 + SDL2 + ffmpeg +OpenAL + java = Android播放器
- 插入排序
- 冒泡排序
- 堆排序
- 快速排序
- 二叉查找树