一、背景

前端时间,自己做的项目需要打包功能,不想再引外部的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. Python和qqbot库开发简单的机器人

    from qqbot import QQBotSlot as qqbotslot, RunBot @qqbotslot def onQQMessage(bot, contact, member, co ...

  2. C. Magic Ship (思维+二分)

    https://codeforces.com/contest/1117/problem/C 你是一个船长.最初你在点 (x1,y1) (显然,大海上的所有点都可以用平面直角坐标描述),你想去点 (x2 ...

  3. [转] PuTTY + Xming 远程使用 Linux GUI

    [From] http://www.zw1840.com/blog/zw1840/2008/10/putty-xming-linux-gui.html By zw1840 on October 28, ...

  4. 解决 TwebBrowser 不能隐藏的问题

    TOleControl(WebBrowser1).Visible := False

  5. python 爬虫系列05--丑事百科

    丑事百科爬虫 import re import requests def parse_page(url): headers = { 'User-Agent':'user-agent: Mozilla/ ...

  6. 【ORACLE】sqlplus使用记录

    1.设置输出长度 SEGMENT_NAME--------------------------- BYTES----------TZ01_LOGIN_DATA 20971520 TZ02_EP_GAT ...

  7. 06-struts2与ognl的结合

    1 参数接收 2 配置文件中 1 Demo2Action package www.test.c_config; import com.opensymphony.xwork2.ActionSupport ...

  8. vs2013下c++调用python脚本函数 出现的一些问题总结

    原文作者:aircraft 原文地址:https://www.cnblogs.com/DOMLX/p/9530834.html 首先是配置: 使用VS2013创建工程. 将libs中的python27 ...

  9. 【数据库】Oracle中删除新建并授权用户

    DROP USER fengw_110 CASCADE; CREATE USER fengw_110 IDENTIFIED BY root123; grant connect,resource,cre ...

  10. Java反射机制一 概念和简单的使用方法。

    一 概念 java反射机制属于 java动态性之一  ,指的是可以运行时加载,探知,使用编译期间完全未知的类,程序在运行状态中,可以动态的加载一个只有, 名称的类,对于任意一个已加载的类,都能够知道这 ...