Java 解压缩 Zip文件(在李兴华老师基础上优化)

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipInputStream;




public class UnZipDemo 
{

	public static void main(String [] args) throws IOException
	{
		File file = new File("F:"+File.separator+"SWT_Designer.zip");//要解压的文件
	
		File outFile = null;
		ZipFile zipFile = new ZipFile(file);//创建压缩文件对象
		ZipInputStream zi = null;
		
		InputStream is = null;
		OutputStream os = null;
		ZipEntry entry = null ;	// 每一个压缩实体
		
		zi = new ZipInputStream(new FileInputStream(file));// 实例化ZIpInputStream
		
		String dir = file.getName().substring(0, file.getName().length()-3);//解压后的文件夹名和压缩文件名(不加拓展名)相同
		
		while((entry=zi.getNextEntry())!=null)//得到一个压缩实体
		{
			System.out.println("解压缩" + entry.getName() + "文件。") ;
			outFile = new File("F:"+ File.separator  + dir+ File.separator + entry.getName()) ;	// 定义输出的文件路径
		    
			if(!outFile.getParentFile().exists())    	
		    {
		    	outFile.getParentFile().mkdir();
		    }
			
			if(!outFile.exists())    	
		    {
				if(outFile.isDirectory()||entry.isDirectory())
				{
					outFile.mkdir();
				}else{
					outFile.createNewFile();
				}
		    }
		
		
		
			
			
			is = zipFile.getInputStream(entry) ;	// 得到每一个实体的输入流

			
		if(outFile.isDirectory())
		{
			continue;
		}else
		{
			os = new FileOutputStream(outFile);
				int len = 0;
				byte [] buf = new byte[1024*10];
				while((len = is.read(buf))!=-1)	
				{
					os.write(buf, 0, len);
				}
					is.close();
					os.close();
					entry.clone();
					
					
				
			}
			
			
		
		}
		zi.close();
			
	}
}







你可能感兴趣的:(Java基础)