一、背景

前端时间,自己做的项目需要打包功能,不想再引外部的jar包

便用java.util.zip做了下该功能

二、适用场景

生成多个word、excel、xml等文件,并要求打包下载的情形

例:项目信息的多选导出word

三、实现

实现分为三个部分,分别是

1、将字符串保存为文件,都是最基本的IO操作

    /**
* @Description 将字符串保存为文件
* @author liuy-8
* @date 2015年5月20日 下午1:48:18
* @param filePath
* @param content
*/
public static void saveFile(String filePath, String content){
File file = new File(filePath);
FileWriter fw = null;
//这里没有使用BufferWrite,是因为数据是一次性写入
//BufferWrite的优势在于调用write方法时,使用缓冲区
//而FileWriter每次调用write方法,都调用StreamEncoder的write方法
try {
fw = new FileWriter(file);//缓冲区1024字符
fw.write(content);
fw.flush();
} catch (IOException e) {
e.printStackTrace();
} finally{
//关闭FileWriter
try {
if(null != fw)
fw.close();
} catch (IOException e) {
e.printStackTrace();
} }
}

2、扫描指定文件夹下所有的文件,准备压缩包的写入工作

这一部分依然是基本的IO操作,要注意安全关闭输入输出流,打开与关闭的顺序

    /**
* @Description 获取文件夹中所有文件路径
* @author liuy-8
* @date 2015年5月27日 下午5:25:24
* @param folderPath 文件夹路径
* @return 文件夹中所有文件路径
*/
public static List<String> getFilesPath(String folderPath){
List<String> filesPath = new ArrayList<String>();
File folder = new File(folderPath);
File[] fileList = folder.listFiles();
for(File file : fileList){
if(file.isDirectory()){
//是文件夹,递归遍历
filesPath.addAll(getFilesPath(file.getPath()));
}else{
//是文件,加入文件列表
filesPath.add(file.getPath());
}
}
return filesPath;
} /**
* @Description 压缩文件夹
* @author liuy-8
* @date 2015年5月26日 下午1:42:00
* @param folderPath 文件夹路径
* @param zipFilePath 压缩文件路径
*/
public static void folder2Zip(String folderPath, String zipFilePath){
//获取当前系统文件分隔符
String fileSeparator = System.getProperty("file.separator");
//若传入路径最后没有文件分隔符,加上
if(folderPath.lastIndexOf(fileSeparator) != (folderPath.length() - 1)){
folderPath = folderPath + fileSeparator;
}
//获取文件夹下所有文件路径
List<String> filesPath = getFilesPath(folderPath);
//文件输出流
FileOutputStream fos = null;
//缓冲输出流
BufferedOutputStream bos = null;
//zip输出流
ZipOutputStream zos = null;
try {
fos = new FileOutputStream(zipFilePath);
bos = new BufferedOutputStream(fos);
zos = new ZipOutputStream(bos);
for(String filePath : filesPath){
//将文件写入zip输出流
writeFile2Zip(folderPath, filePath, zos);
}
zos.flush();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally{
//关闭zip输出流
try {
if(null != zos){
zos.close();
}
} catch (IOException e) {
e.printStackTrace();
}
//关闭缓冲输出流
try {
if(null != bos){
bos.close();
}
} catch (IOException e) {
e.printStackTrace();
}
//关闭文件输出流
try {
if(null != fos){
fos.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}

3、将文件依次写入zip输出流

在第二步已经用ZipOutputStream创建了压缩文件的输出流,这一步里,每个文件都要对应一个ZipEntry对象

要将这个对象加入到压缩文件的输出流中后再写入数据,并且写完数据必须在输出流中关闭该ZipEntry对象

这里有2个容易出错的地方:

一是ZipEntry对象需要一个路径,这个路径是相对于压缩文件夹的相对路径,用来保证子文件夹文件的顺利压入

二是往zip输出流中写入的字节的时候,要判断循环读取字节时文件输入流中读取了多少字节长度,读多少写多少,不然在文件尾部会出现错误数据

    /**
* @Description 将文件写入zip输出流
* @author liuy-8
* @date 2015年5月27日 下午5:23:42
* @param folderPath 待压缩文件夹路径
* @param filePath 待写入文件
* @param zos zip输出流
*/
private static void writeFile2Zip(String folderPath, String filePath, ZipOutputStream zos){
//缓冲区
byte[] bs = new byte[1024];
//获取文件的相对路径
String entryName = filePath.substring(filePath.indexOf(folderPath) + folderPath.length());
//创建zip实体
ZipEntry entry = new ZipEntry(entryName);
//输入流
FileInputStream fis = null;
//缓冲输入流
BufferedInputStream bis = null;
try {
//将zip实体加入zip输出流
zos.putNextEntry(entry);
fis = new FileInputStream(filePath);
bis = new BufferedInputStream(fis);
//写入zip输出流
int len = 0;
while((len = bis.read(bs, 0, 1024)) > 0){
zos.write(bs, 0, len);
}
zos.flush();
} catch (IOException e) {
e.printStackTrace();
} finally{
//关闭entity
try {
zos.closeEntry();
} catch (IOException e) {
e.printStackTrace();
}
//关闭BufferedInputStream
try {
if(null != bis){
bis.close();
}
} catch (IOException e) {
e.printStackTrace();
}
//关闭FileInputStream
try {
if(null != fis){
bis.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}

此类已封装为GlodonFileUtil,有需要找我要即可

java原生文件打包的更多相关文章

  1. Java批量文件打包下载

    经常遇到选择多个文件进行批量下载的情况,可以先将选择的所有的文件生成一个zip文件,然后再下载,该zip文件,即可实现批量下载,但是在打包过程中,常常也会出现下载过来的zip文件中里面有乱码的文件名, ...

  2. java将文件打包成ZIP压缩文件的工具类实例

    package com.lanp; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import ja ...

  3. Java批量文件打包下载zip

    网上看了很多,本文使用ant.jar中的org.apache.tools.zip,页面用js表单提交 代码供参考: ACTION: /* * 另存为 */ @RequestMapping(" ...

  4. 【Java】Java批量文件打包下载zip

    网上看了很多,本文使用ant.jar中的org.apache.tools.zip,页面用js表单提交 代码供参考: ACTION: /*      * 另存为      */     @Request ...

  5. java jar文件打包成exe(Launch4j使用说明)

    在日常的项目中需要把jar打包成exe.怎样快速的实现此功能.下面通过Launch4j的使用方法来介绍整个打包过程. 第一步:生成jar文件 第二部:使用Launch4j 图来描述过,简单明了.一切尽 ...

  6. Java 实现文件上传、下载、打包、文件copy、文件夹copy。

    文件and文件夹copy package org.test; import java.io.*; public class FileCopy { /** * 复制单个文件 * * @param old ...

  7. 手把手教你如何把java代码,打包成jar文件以及转换为exe可执行文件

    1.背景: 学习java时,教材中关于如题问题,只有一小节说明,而且要自己写麻烦的配置文件,最终结果却只能转换为jar文件.实在是心有不爽.此篇博客教你如何方便快捷地把java代码,打包成jar文件以 ...

  8. 把java文件打包成.jar (jar命令详解)

    把java文件打包成.jar (jar命令详解) 先打开命令提示符(win2000或在运行框里执行cmd命令,win98为DOS提示符),输入jar Chelp,然后回车(如果你盘上已经有了jdk1. ...

  9. 使用Eclipse把java文件打包成jar 含有第三方jar库的jar包

    使用Eclipse把java文件打包成jar 含有第三方jar库的jar包   网上打包说用eclipse安装fat jar插件,但是貌似现在都不能用了,所以我只能按照eclipse自带的方法打包了. ...

随机推荐

  1. Android 查看联系人电话和姓名(ContentProvider)

    1.介绍 2.使用方法 3.在AndroidManifest.xml文件中添加相关设置 <uses-permission android:name="android.permissio ...

  2. paraview添加vector

    https://youtu.be/cygVdhn-kG0 (须自行FQ)

  3. PHP7 关于变量的基本判断

    刚学 PHP ,一些基础还不太牢固,边实践边记录. about NULL $class_name = null; 语句结束后,$class_name 是空,没有,什么都没有的“空”.用 is_null ...

  4. 洛谷 P3380 【模板】二逼平衡树(树套树)

    题面 luogu 题解 2019年AC的第一道题~~ 函数名命名为rank竟然会ce 我写的是树状数组套值域线段树(动态开点) 操作1:询问\(k\)在\([l-r]\)这段区间有多少数比它小,再加\ ...

  5. git 如何删除远程提交方法总结

    今天不小心把代码提到主分支了,虽然改动只有一点点,但感觉asdasdasdsadd(要被骂死) 怎么样才能删除掉远程的分支呢. 假设我们有提交 commit commit commit 手残把3提交错 ...

  6. EntityFramework 并发处理

    转载自:http://www.cnblogs.com/TianFang/p/4439215.html 什么是并发? 并发分悲观并发和乐观并发. 悲观并发:比如有两个用户A,B,同时登录系统修改一个文档 ...

  7. webAPI过滤器返回数据加密

    项目需求: 接口返回的数据,存在一些敏感信息,不希望其他用户看到,将Data进行加密传输 代码如下: public class EncryptDataFilterAttribute : ActionF ...

  8. 网站ico那点事儿

    一. 如何获取某个网站的favicon.ico http://moco.imooc.com/player/report.html 今天看到这个网站上,左侧的小图片挺好看的,想弄下来,检查源码,也没有看 ...

  9. oracle 基础知识(十一)----表空间结构

    一,逻辑结构图 二.tablespace 01,Oracle表空间 它是一个逻辑的概念,它在物理上是不存在的. 02,oracle 存储结构 03.表空间特性 一个数据库可以包含多个表空间,一个表空间 ...

  10. mysql 存储过程(proceduce)查询一个表的结果插入另外一个表

    公司的时间戳存证业务,对发版过程中间数据处理需要用到存储过程.对此做一个简短记录,以免遗忘. DROP procedure record_timestamp_deal ; ##创建存储过程 creat ...