今天在公司,应老板要求,把以前是对一个文件打成一个zip,变成相同类别的文件打成一个zip,就是多文件打包,想破了脑袋,搜了度娘,再结合自己的想法谢了方法二,方法一是转载的!
方法一:
public static HttpServletResponse downLoadFiles(List<File> files,HttpServletResponse response)throws Exception {
try {
//List<File> 作为参数传进来,就是把多个文件的路径放到一个list里面
//创建一个临时压缩文件
//临时文件可以放在CDEF盘中,但不建议这么做,因为需要先设置磁盘的访问权限,最好是放在服务器上,方法最后有删除临时文件的步骤
String zipFilename = "D:/tempFile.zip" ;
File file = new File(zipFilename);
if (!file.exists()){
file.createNewFile();
}
response.reset();
//response.getWriter()
//创建文件输出流
FileOutputStream fous = new FileOutputStream(file);
ZipOutputStream zipOut = new ZipOutputStream(fous);
zipFile(files, zipOut);
zipOut.close();
fous.close();
return downloadZip(file,response);
}catch (Exception e) {
e.printStackTrace();
}
return response ;
}
/**
* 把接受的全部文件打成压缩包
* @param List<File>;
* @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);
}
}
/**
* 根据输入的文件与输出流对文件进行打包
* @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);
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();
}
}
public static HttpServletResponse downloadZip(File file,HttpServletResponse response) {
if(file.exists() == false){
System.out.println("待压缩的文件目录:"+file+"不存在.");
}else{
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");
//如果输出的是中文名的文件,在此处就要用URLEncoder.encode方法进行处理
response.setHeader("Content-Disposition", "attachment;filename="
+ new String(file.getName().getBytes("GB2312"), "ISO8859-1"));
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;
}
方法二: 主要是writeZip 方法,传入数组,数组里面是文件的地址,为了实现老板需求,我在前面先把同一类型的文件放到一个数组中,剩下的参数是打包的文件名称和打包后文件的路径,在调用这个方法就ok了,剩下 的方法是度娘查的,对于zip包的下载等等!
//压缩文件(防止中文乱码----使用apache的ZipOutputStream包)
private static void writeZip(String[] strs,String zipname,String temppath) throws IOException {
String[] files = strs;
OutputStream os = new BufferedOutputStream(new FileOutputStream(temppath+"//"+zipname));
ZipOutputStream zos = new ZipOutputStream(os);
byte[] buf = new byte[8192];
int len;
for (int i=0;i<files.length;i++) {
File file = new File(files[i]);
if ( !file.isFile() ) continue;
ZipEntry ze = new ZipEntry( file.getName() );
zos.putNextEntry(ze);
BufferedInputStream bis = new BufferedInputStream( new FileInputStream( file ) );
while ( ( len = bis.read( buf ) ) > 0 ) {
zos.write( buf, 0, len );
}
zos.closeEntry();
bis.close();
}
zos.setEncoding("GBK");
for(int i=0;i<files.length;i++){
File file= new File(files[i]);
file.delete();
}
zos.closeEntry();
zos.close();
os.close();
}
/**
* 递归查找文件
* @param baseDirName 查找的文件夹路径
* @param targetFileName 需要查找的文件名
* @param fileList 查找到的文件集合
*/
public static void findFiles(String baseDirName, String targetFileName, List fileList) {
File baseDir = new File(baseDirName); // 创建一个File对象
if (!baseDir.exists() || !baseDir.isDirectory()) { // 判断目录是否存在
System.out.println("文件查找失败:" + baseDirName + "不是一个目录!");
}
String tempName = null;
//判断目录是否存在
File tempFile;
File[] files = baseDir.listFiles();
for (int i = 0; i < files.length; i++) {
tempFile = files[i];
if(tempFile.isDirectory()){
findFiles(tempFile.getAbsolutePath(), targetFileName, fileList);
}else if(tempFile.isFile()){
tempName = tempFile.getName();
if(wildcardMatch(targetFileName, tempName)){
// 匹配成功,将文件名添加到结果集
fileList.add(tempFile.getAbsoluteFile());
}
}
}
}
/**
* 删除zip
*/
public void deleteZip(String path) {
/* String[] sos = abpath.split("/");
String name = ss[ss.length - 1];
String path = abpath.replace("/" + name, "");*/
File file = new File(path);// 里面输入特定目录
File temp = null;
File[] filelist = file.listFiles();
for (int i = 0; i < filelist.length; i++) {
temp = filelist[i];
if (temp.getName().endsWith("zip"))// 获得文件名,如果后缀为“”,这个你自己写,就删除文件
{
temp.delete();// 删除文件}
}
}
}
导出zip
Date now = new Date();
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd_HHmmss");//可以方便地修改日期格
String tm= dateFormat.format(new Date());
String zipname=tm+".zip";
writeZip(fils,zipname,temppath);//服务端生成zip文件
InputStream in = in = new FileInputStream(temppath+"//"+zipname); //获取文件的流
OutputStream os = response.getOutputStream();
int len = 0;
byte buf[] = new byte[1024];//缓存作用
response.setCharacterEncoding("UTF-8");
response.setContentType("application/octet-stream; charset=UTF-8");
response.addHeader("Content-Disposition", "attachment; filename=\""+new String(zipname.getBytes("GB2312"),"ISO8859-1")+"\";");//
os = response.getOutputStream();//输出流
while( (len = in.read(buf)) > 0 ) //切忌这后面不能加 分号 ”;“
{
os.write(buf, 0, len);//向客户端输出,实际是把数据存放在response中,然后web服务器再去response中读取
}
in.close();
os.close();
deleteZip(temppath);//导出后删除zip
/**
* 追加文件:使用FileWriter---写入
*/
public static void appendMethodB(String fileName, StringBuffer content) {
try {
//打开一个写文件器,构造函数中的第二个参数true表示以追加形式写文件
FileWriter writer = new FileWriter(fileName, true);
/*OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream(fileName, true),"UTF-8");
osw.write(content);
osw.close();*/
writer.write(content.toString());
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 功能:Java读取txt文件的内容
* 步骤:1:先获得文件句柄
* 2:获得文件句柄当做是输入一个字节码流,需要对这个输入流进行读取
* 3:读取到输入流后,需要读取生成字节流
* 4:一行一行的输出。readline()。
* 备注:需要考虑的是异常情况
* @param filePath
*/
public static ArrayList<String> readTxtFile(String filePath){
ArrayList<String> readList = new ArrayList<String>();
try {
String encoding="GBK";
File file=new File(filePath);
if(file.isFile() && file.exists()){ //判断文件是否存在
InputStreamReader read = new InputStreamReader(
new FileInputStream(file),encoding);//考虑到编码格式
BufferedReader bufferedReader = new BufferedReader(read);
String lineTxt = null;
while((lineTxt = bufferedReader.readLine()) != null){
readList.add(lineTxt);
}
read.close();
}else{
System.out.println("找不到指定的文件");
}
} catch (Exception e) {
System.out.println("读取文件内容出错");
e.printStackTrace();
}
return readList;
}