java zip 压缩文件

zip压缩:ZipOutputStream、ZipFile、ZipInputStream 三个类的作用

 

 

一段 java  zip  压缩的代码:

 

                File dir = new File("C:\\Users\\Administrator\\Desktop\\zipsource");
		String zipFile = "C:\\Users\\Administrator\\Desktop\\test2.zip";
		
		
		OutputStream outputStream = new FileOutputStream(new File(zipFile));
		ZipOutputStream zipOutputStream = new ZipOutputStream(outputStream);
		

		byte[] buffer = new byte[1024];
		int len  = 0;
		
		
		if( dir.isDirectory() ) {
			 File[]  files = dir.listFiles();
			for(File fileItem  :files) {
				FileInputStream fileItemInputStream = new FileInputStream( fileItem );
				ZipEntry zipEntry = new ZipEntry( fileItem.getName() );
				zipOutputStream.putNextEntry( zipEntry );
				while( (len = IOUtils.read(fileItemInputStream, buffer)) != 0 ) {
					zipOutputStream.write( buffer,0,len );
				}
				fileItemInputStream.close();
			}
		}
		zipOutputStream.flush();
		zipOutputStream.close();

  

 

 

 

备注:apache  commons-compress 中有很多关于压缩的 工具类

posted on 2018-08-09 12:16  zhangyukun  阅读(147)  评论(0编辑  收藏  举报

导航