一、涉及到的包都是jdk自带的。(所以不用为包的事发愁了)
二、啥也不说了,把demo献上
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
public class ZipUtil {
public static void main(String[] args) {
List<File> files= new ArrayList<File>();
File file=new File("E:\\file\\原来你也在这里.mp3");
files.add(file);
File file1=new File("E:\\file\\dd.zip");
compression(files,file1);
}
public static boolean compression(List<File> sourceFiles,File zipFilePath){
boolean flag=false;
FileOutputStream fos=null;
ZipOutputStream zos=null;
FileInputStream fis=null;
BufferedInputStream bis=null;
try {
if (sourceFiles!=null&&sourceFiles.size()!=0) {
fos=new FileOutputStream(zipFilePath);
zos=new ZipOutputStream(new BufferedOutputStream(fos));
byte[] bufs=new byte[1024*10];
for (int i = 0; i < sourceFiles.size(); i++) {
ZipEntry zipEntity=new ZipEntry(sourceFiles.get(i).getName());
zos.putNextEntry(zipEntity);
//读取压缩文件并写入压缩包
fis=new FileInputStream(sourceFiles.get(i));
bis=new BufferedInputStream(fis,1024*10);
int read=0;
while ((read=bis.read(bufs,0,1024*10))!=-1) {
zos.write(bufs, 0, read);
}
flag = true;
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
throw new RuntimeException(e);
// TODO: handle exception
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
throw new RuntimeException(e);
}finally{
try {
if(zos!=null){
zos.flush();
zos.close();
}
if (fis!=null) {
fis.close();
}
if (bis!=null) {
bis.close();
}
if (fos!=null) {
fos.flush();
fos.close();
}
} catch (IOException e) {
e.printStackTrace();
throw new RuntimeException(e);
// TODO: handle exception
}
}
return flag;
}
}
流用完一定记得关