`
lg_asus
  • 浏览: 184308 次
  • 性别: Icon_minigender_1
  • 来自: 苏州
社区版块
存档分类
最新评论

java压缩与解压缩

 
阅读更多
public class Test5 {

	public static void main(String...args){
		ZipOutputStream zos = null;
		ZipInputStream zis = null;
		try{
			File file = new File("E:\\TDDOWNLOAD");
			CheckedOutputStream cos = new CheckedOutputStream(new FileOutputStream("E:\\TDDOWNLOAD.zip"), new CRC32());
			zos = new ZipOutputStream(cos);
			compress("",file,zos);
			zos.close();
			//checkSum valid only after file has been closed
			long checkSum = cos.getChecksum().getValue();
			System.out.println(checkSum);
			
			CheckedInputStream cis = new CheckedInputStream(new FileInputStream("E:\\TDDOWNLOAD.zip"), new CRC32());
			zis = new ZipInputStream(cis);
			uncompress("E:\\",zis);
			zis.close();
			long checkSum2 = cis.getChecksum().getValue();
			System.out.println(checkSum2);
		}catch(IOException e){
			e.printStackTrace();
		}finally{
			if(zos != null){
				try {
					zos.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if(zis != null){
				try {
					zis.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}

	private static void compress(String parentPath, File file, ZipOutputStream zos) throws IOException{
		if(file.isHidden() || !file.canRead()){
			return ;
		}
		if(file.isFile()){
			ZipEntry entry = new ZipEntry(parentPath+file.getName());
			zos.putNextEntry(entry);
			BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file),8192);
			int count = 0;
			byte[] b = new byte[8192];
			while((count=bis.read(b))!=-1){
				zos.write(b,0,count);
			}
			zos.closeEntry();
			zos.flush();
			bis.close();
		}else{
			//压缩空目录
			ZipEntry entry = new ZipEntry(parentPath+file.getName()+"/");
			zos.putNextEntry(entry);
			zos.closeEntry();
			zos.flush();
			//end
			
			File[] subFiles = file.listFiles();
			for(int i=0;i<subFiles.length;i++){
				compress(parentPath+file.getName()+"/", subFiles[i],zos);
			}
		}
	}
	

	private static void uncompress(String parentPath, ZipInputStream zis) throws IOException {
		ZipEntry entry = null;
		String filePath = null;
		String dir = null;
		String fileName = null;
		File file = null;
		byte[] b = new byte[8192];
		while((entry=zis.getNextEntry())!=null){
			filePath = parentPath+entry.getName();
			if(entry.isDirectory()){
				dir = filePath.substring(0, filePath.lastIndexOf("/"));
				new File(dir).mkdirs();
			}else{
				file = new File(filePath);
				file.createNewFile();
				FileOutputStream fos = new FileOutputStream(file);
				int count = 0;
				while((count=zis.read(b))!=-1){
					fos.write(b,0,count);
				}
				fos.close();
			}
		}
	}
}



我不明白的是:为什么每次压缩产生的校验和是不同的?
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics