java生成zip包
Posted 牛奶糖13号
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java生成zip包相关的知识,希望对你有一定的参考价值。
package common.util;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
public class ZipUtils {
/** 压缩单个文件*/
public static void zipFile(String filepath ,String zippath) {
//String s = UUID.randomUUID().toString();为了怕后面删除这个临时文件是删除到同一个文件
//这里filepath为要打包的文件夹的路径String filepath = ServletActionContext.getServletContext().getRealPath("upload/notice/"+s+"/");
//zippath为生成的zip包的路径String zippath = ServletActionContext.getServletContext().getRealPath("upload/notice/"+s+"/week-job.zip");这里生成的就是个week-job.zip包
//ServletActionContext.getServletContext().getRealPath();获得服务器地址
InputStream input = null;
ZipOutputStream zipOut = null;
try {
File file = new File(filepath);
File zipFile = new File(zippath);
input = new FileInputStream(file);
zipOut = new ZipOutputStream(new FileOutputStream(zipFile));
zipOut.putNextEntry(new ZipEntry(file.getName()));
int temp = 0;
while((temp = input.read()) != -1){
zipOut.write(temp);
}
System.out.println("zip "+filepath+" to "+zippath);
} catch (Exception e) {
e.printStackTrace();
}finally{
try {
input.close();
zipOut.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
/** 一次性压缩多个文件,文件存放至一个文件夹中*/
public static void zipMultiFile(String filepath ,String zippath) {
try {
File file = new File(filepath);// 要被压缩的文件夹
File zipFile = new File(zippath);
InputStream input = null;
ZipOutputStream zipOut = new ZipOutputStream(new FileOutputStream(zipFile));
if(file.isDirectory()){
File[] files = file.listFiles();
for(int i = 0; i < files.length; ++i){
input = new FileInputStream(files[i]);
zipOut.putNextEntry(new ZipEntry(file.getName() + File.separator + files[i].getName()));
int temp = 0;
while((temp = input.read()) != -1){
zipOut.write(temp);
}
input.close();
}
}else{//否则,则调用压缩单个文件的方法
zipFile(filepath, zippath);
}
zipOut.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
以上是关于java生成zip包的主要内容,如果未能解决你的问题,请参考以下文章