java压缩文件

来源:互联网 发布:mac卸载第三方软件 编辑:程序博客网 时间:2024/05/19 21:01
Java代码 复制代码 收藏代码
  1. /**  
  2.      * 压缩文件  
  3.      *   
  4.      * @method zip_file  
  5.      * @param file_path 需压缩的文件路径  
  6.      */  
  7.     private void zip_file(String file_path){   
  8.         File file = new File(file_path);   
  9.         FileInputStream fileInputStream = null;   
  10.         BufferedInputStream bufferedInputStream = null;   
  11.         ZipOutputStream zipOutputStream = null;   
  12.         try {   
  13.             fileInputStream = new FileInputStream(file);   
  14.             bufferedInputStream = new BufferedInputStream(fileInputStream);   
  15.             byte[] buf = new byte[1024];   
  16.             int len;   
  17.             FileOutputStream fileOutputStream = new FileOutputStream(GlobalVar.serverConfig.getProperty("vasserver.adcftp.srcdir")+file.getName()+".ZIP");   
  18.             BufferedOutputStream bos = new BufferedOutputStream(fileOutputStream);   
  19.             zipOutputStream = new ZipOutputStream(bos);//压缩包  
  20.             ZipEntry zipEntry = new ZipEntry(file.getName());//压缩包里的文件名称  
  21.             zipOutputStream.putNextEntry(zipEntry);//写入新的 ZIP 文件条目并将流定位到条目数据的开始处  
  22.             while(-1 != (len=bufferedInputStream.read(buf))){   
  23.                 zipOutputStream.write(buf, 0, len);   
  24.                 zipOutputStream.flush();   
  25.             }   
  26.                
  27.         } catch (FileNotFoundException e) {   
  28.             log.error("未找到需压缩的文件!-->" + e.getMessage());   
  29.             e.printStackTrace();   
  30.             System.out.println("未找到需压缩的文件!-->" + e.getMessage());   
  31.         } catch (IOException e) {   
  32.             log.error("文件压缩异常!-->" + e.getMessage());   
  33.             e.printStackTrace();   
  34.             System.out.println("文件压缩异常!-->" + e.getMessage());   
  35.         } finally {   
  36.             try {   
  37.                 if(null != zipOutputStream)   
  38.                     zipOutputStream.close();   
  39.                 if(null != bufferedInputStream)   
  40.                     bufferedInputStream.close();   
  41.             } catch (IOException e) {   
  42.                 e.printStackTrace();   
  43.             }   
  44.                
  45.         }   
  46.     }  
原创粉丝点击