- package compress.javaio;
- import java.io.*;
- import java.util.zip.*;
- public class CompressFiles{
- /**
- * @param args
- * @throws IOException
- */
- public static void main(String[] args) throws IOException {
- // TODO Auto-generated method stub
- String sourPath=File.separator+"root"+File.separator+"ziptest02";
- File file=new File(sourPath);
- ZipOutputStream zipOut=null;//此对象需在主函数中创建
- zipOut=new ZipOutputStream(new FileOutputStream(File.separator+"root"+File.separator+"ziptest02.zip"));
- String str=file.getName();
- Recurrence(file,zipOut,str);//调用递归函数,判断该当前项是目录或者文件
- zipOut.close();
- System.out.println("压缩流已经关闭");
- }
- private static void Recurrence(File file,ZipOutputStream zipOut,String str) throws IOException{
- //TODO 判断该项是否是文件,若是文件,直接传给Compress()函数处理
- if(file.isDirectory()){
- File files[]=file.listFiles();
- for(int i=0;i<files.length;i++){
- Recurrence(files[i],zipOut,str);
- }
- }else{
- Compress(file,zipOut,str);
- }
- }
- private static void Compress(File file,ZipOutputStream zipOut,String str) throws IOException {
- // TODO Auto-generated method stub
- InputStream input=null;
- input=new FileInputStream(file);
- //String str1=str+File.separator+file.getName();
- System.out.println("此次处理文件为:"+file.getPath());
- ZipEntry entry=new ZipEntry(file.getPath());
- zipOut.putNextEntry(entry);
- int temp=0;
- while((temp=input.read())!=-1){
- zipOut.write(temp);
- }
- input.close();
- }
- }
本文出自 “秦楼客” 博客,请务必保留此出处http://qinlouke.blog.51cto.com/1417650/901382