java打包文件夹为zip文件

 1 //待压缩的文件目录
 2 String sourceFile=sourceFilePath+"\\"+userName;
 3 //存放压缩文件的目录
 4 String zipFilePath = sourceFilePath;  
 5 //zip文件名字,不加zip 方法里面有
 6 fileName=“**** 7 
 8 //直接粘贴 
 9 public Object fileZip(String sourceFilePath,String zipFilePath,String fileName){  
10        String flag = "";  
11        File sourceFile = new File(sourceFilePath);  
12        FileInputStream fis = null;  
13        BufferedInputStream bis = null;  
14        FileOutputStream fos = null;  
15        ZipOutputStream zos = null;  
16          
17        if(sourceFile.exists() == false){  
18            System.out.println("待压缩的文件目录:"+sourceFilePath+"不存在.");  
19        }else{  
20            try {  
21                File zipFile = new File(zipFilePath + "/" + fileName +".zip");  
22                if(zipFile.exists()){  
23                    System.out.println(zipFilePath + "目录下存在名字为:" + fileName +".zip" +"打包文件.");  
24                }else{  
25                    File[] sourceFiles = sourceFile.listFiles();  
26                    if(null == sourceFiles || sourceFiles.length<1){  
27                        System.out.println("待压缩的文件目录:" + sourceFilePath + "里面不存在文件,无需压缩.");  
28                    }else{  
29                        fos = new FileOutputStream(zipFile);  
30                        zos = new ZipOutputStream(new BufferedOutputStream(fos));  
31                        byte[] bufs = new byte[1024*10];  
32                        for(int i=0;i
33                            //创建ZIP实体,并添加进压缩包  
34                            ZipEntry zipEntry = new ZipEntry(sourceFiles[i].getName());  
35                            zos.putNextEntry(zipEntry);  
36                            //读取待压缩的文件并写进压缩包里  
37                            fis = new FileInputStream(sourceFiles[i]);  
38                            bis = new BufferedInputStream(fis, 1024*10);  
39                            int read = 0;  
40                            while((read=bis.read(bufs, 0, 1024*10)) != -1){  
41                                zos.write(bufs,0,read);  
42                            }  
43                        }  
44                        flag = "";  
45                    }  
46                }  
47            } catch (FileNotFoundException e) {  
48                e.printStackTrace();  
49                throw new RuntimeException(e);  
50            } catch (IOException e) {  
51                e.printStackTrace();  
52                throw new RuntimeException(e);  
53            } finally{  
54                //关闭流  
55                try {  
56                    if(null != bis) bis.close();  
57                    if(null != zos) zos.close();  
58                } catch (IOException e) {  
59                    e.printStackTrace();  
60                    throw new RuntimeException(e);  
61                }  
62            }  
63        }  
64        return flag;  
65    }  

 

posted @ 2015-12-22 17:13  道行太浅  阅读(395)  评论(0编辑  收藏  举报