자바 파일 압축 및 압축 풀기 (3)

19227 단어
package com.cn;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipOutputStream;

//    :
//1   file.isFile() file.isDirectory()      .
//        Directory   file,file    Directory
//    :file Directory    .   file Directory     .
//     1            .

//2           File f=new File("F:\\x.txt");
//              x.txt  .        
//       .
//  File f=new File("F:\\x.txt");
//  if (!f.exists()) {
//	   f.createNewFile();
//  }
//   f.createNewFile()          
//
//       ,     File f=new File("F:\\x.txt")
//         ,    f    ,    x.txt   
//   hello world
// 

//3     :
//  zip()        zos.             

//    :
//1   zip unzip             !!!
//        directory,              ,        .
//         ,    directory,               .

//2  JAVA            ZipEntry  
//                       (            )
//               new()  ZipEntry

//3     zipEntry          .        
//             entrys.hasMoreElements()   
//      zipEntry.
//          :
//  new File(unzipPath+File.separator+entry.getName());
	
public class TestZipAndUnZip {
   public static void main(String[] args) throws Exception {
	   TestZipAndUnZip test=new TestZipAndUnZip();
	   //         zip
//	   test.zip("E:\\", "aa\\1.txt", "E:\\cc1.zip");
	   
	   //         zip
	   //test.zip("E:\\aa", "bb\\", "E:\\zz.zip");//right
	  
//	   test.zip("F:\\", "kk", "F:\\zz678910.zip");//right
//
////	   //    zip  
//	   test.unZipFile("F:\\zz678910.zip", "E:\\zzzz");
	   

	   
	   /////////////////////    ///////////////////////////////
	   //         
	   test.zip2("F:\\kk\\cc.txt","F:\\88.zip");
	   test.unZipFile2("F:\\88.zip", "F:\\abc");
	   
	   //         
	   test.zip2("F:\\kk","F:\\9zip.zip");
	   test.unZipFile2("F:\\9zip.zip", "F:\\9files");
	   
	   /////////////////////    //////////////////////////////
   }
   
/**
 * @param willZipDirPath         (  )    
 * @param willZipFileName        (  )   
 * @param toFilePath             (  ) 
 */
	public void zip(String willZipDirPath, String willZipFileName, String zipedFileName) {
		System.out.println("…………………   zip()  …………………………");
		if (willZipDirPath == null) {
			return;
		}
		File willZipDir = new File(willZipDirPath);
		if (!willZipDir.exists() || !willZipDir.isDirectory()) {
			return;
		}
		//         
		String willZipDirAbsolutePath = willZipDir.getAbsolutePath();
		System.out.println("willZipDir.getAbsolutePath()="+willZipDirAbsolutePath);
		//      
		File zipedFile = new File(zipedFileName);
		try {
			//              ZipOutputStream
			//   zos             .     
			//           ?
			//     ZipEntry!!!
			// fileToZip()        ZipEntry   !!
			ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(zipedFile));
			if (willZipFileName.equals("*")) {
				//     *               
				//    dirToZip()
				dirToZip(willZipDirAbsolutePath, willZipDir, zos);
			} else {
				//       
				File willZipFile = new File(willZipDirPath, willZipFileName);
				System.out.println("ccccccccccc name="+willZipFile.getName());
				System.out.println("ccccccccccc getAbsolutePath="+willZipFile.getAbsolutePath());
				
				if (willZipFile.isFile()) {
					System.out.println("…………………         ………………………");
					fileToZip(willZipDirPath, willZipFile, zos);
					System.out.println("…………………         ………………………");
				}
				if (willZipFile.isDirectory()) {
					System.out.println("…………………         ………………………");
					dirToZip(willZipDirPath, willZipFile, zos);
					System.out.println("…………………         ………………………");
				}
				//    !!!
				zos.close();
				System.out.println("…………………   zip()  …………………………");
			}
		} catch (Exception e) {
			// TODO: handle exception
		}

	}
	
   /**
 * @param dirPath               
 * @param willZipFile          
 * @param zos             
 */
public void fileToZip(String dirPath, File willZipFile,ZipOutputStream zos){
	   FileInputStream fis=null;
	   ZipEntry zipEntry=null;
	   byte [] buffer=new byte[1024*8];
	   int len=0;
	   if (willZipFile.isFile()) {
		try {
			fis=new FileInputStream(willZipFile);
			zipEntry=new ZipEntry(getEntryName(dirPath, willZipFile));
			zos.putNextEntry(zipEntry);
			System.out.println("…………………   fileToZip()  …………………………");
			System.out.println("zipEntry.getName="+zipEntry.getName());
			System.out.println("zipEntry.isDirectory="+zipEntry.isDirectory());
			System.out.println("zipEntry.getSize="+zipEntry.getSize());
			System.out.println("zipEntry.getTime="+zipEntry.getTime());
			System.out.println("zipEntry.getComment="+zipEntry.getComment());
			System.out.println("…………………   fileToZip()  …………………………");
			while((len=fis.read(buffer))!=-1){
				zos.write(buffer, 0, len);
			}
			zos.closeEntry();
			fis.close();
		} catch (Exception e) {
		}
	}
  }

	/**
	 * @param dirPath                 
	 * @param willZipDir       
	 * @param zos            
	 */
	public void dirToZip(String dirPath, File willZipDir, ZipOutputStream zos) {
		if (willZipDir.isDirectory()) {
			File[] files = willZipDir.listFiles();
			
			//  -->        
            if (files.length==0) {
				ZipEntry zipEntry=new ZipEntry(getEntryName(dirPath, willZipDir));
				System.out.println("xxxxxxxxxxxxxxxx "+zipEntry.getName());
				try {
					zos.putNextEntry(zipEntry);
					//zos.closeEntry();
				} catch (Exception e) {
					e.printStackTrace();
				}
				return;
			}
            //  -->          
            for (int i = 0; i < files.length; i++) {
				File file = files[i];
				//    ,    fileToZip()
				if (file.isFile()) {
					System.out.println("xxxxxxxxxx    fileToZip()  xxxxxxxxxx");
					fileToZip(dirPath, file, zos);
					System.out.println("xxxxxxxxxx  fileToZip()    xxxxxxxxxx");
				}
				//    ,    dirToZip()
				if (file.isDirectory()) {
					System.out.println("xxxxxxxxxx    dirToZip()  xxxxxxxxxx");
					dirToZip(dirPath, file, zos);
					System.out.println("xxxxxxxxxx  dirToZip()    xxxxxxxxxx");
				}
			}
		}
	}
   
	/**
	 * @param dirPath                
	 * @param willZipFile         
	 * @return            
	 */
	//             (            )
	//     zipEntry           .        
	public String getEntryName(String dirPath, File willZipFile) {
		if (!dirPath.endsWith(File.separator)) {
			dirPath += File.separator;
		}
		String willZipFilePath=willZipFile.getAbsolutePath();
		if (willZipFile.isDirectory()) {
			willZipFilePath+="/";
		}
		int index=willZipFilePath.indexOf(dirPath);
		
		System.out.println("xx    entryName="+ willZipFilePath.substring(index+dirPath.length()));
		return willZipFilePath.substring(index+dirPath.length());
	}
	
	
	
	
	/**
	 * @param zipedFileName    zip  
	 * @param unzipDirPath              
	 * @throws IOException 
	 */
	public void unZipFile(String zipedFileName,String unzipDirPath) throws Exception{
	
		if (!unzipDirPath.endsWith(File.separator)) {
			unzipDirPath+=File.separator;
		}
		
		try {
			ZipFile zipedFile=new ZipFile(zipedFileName);
			ZipEntry zipEntry=null;
			String entryName=null;
			String unzipedFileName=null;
			Enumeration entrys=zipedFile.entries();
			byte [] buffer=new byte[1024*8];
			int len=0;
			while (entrys.hasMoreElements()) {
				zipEntry=(ZipEntry) entrys.nextElement();
				entryName=zipEntry.getName();
				unzipedFileName=unzipDirPath+entryName;
				System.out.println("…………………   unZipFile()  …………………………");
				System.out.println("zipedFileName="+zipedFileName);
				System.out.println("unzipDirPath="+unzipDirPath);
				System.out.println("entryName="+entryName);
				System.out.println("unzipedFileName="+unzipedFileName);
				System.out.println("…………………   unZipFile()  …………………………");
				if (zipEntry.isDirectory()) {
					//       
					System.out.println("999999999999");
					new File(unzipedFileName).mkdirs();
				} else {
					//       .                  .
                    new File(unzipedFileName).getParentFile().mkdirs();
				}
				FileOutputStream fos=null;
				InputStream is=null;
				File unzipedFile=new File(unzipedFileName);
				if (unzipedFile.isDirectory()) {
					File [] files=unzipedFile.listFiles();
					for (int i = 0; i < files.length; i++) {
						File file = files[i];
						 fos=new FileOutputStream(file);
						 is=zipedFile.getInputStream(zipEntry);
						while ((len=is.read(buffer))!=-1) {
							fos.write(buffer, 0, len);
						}
					}
				}else{
				 fos=new FileOutputStream(unzipedFile);
				 is=zipedFile.getInputStream(zipEntry);
				   while ((len=is.read(buffer))!=-1) {
					fos.write(buffer, 0, len);
				}
				}
				//      
				//fos.close();
				//is.close();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/////////////////////////////////////////////////////////////////////////////////////
	/**
	 *                
	 * @param willZipPath         
	 * @param zipedPath            
	 */
	public void zip2(String willZipPath, String zipedPath) {
		try {
			File willZipFile = new File(willZipPath);
			File zipedFile = new File(zipedPath);
			ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(zipedFile));
			if (willZipFile.isFile()) {
				fileToZip2(willZipPath, zos);
			}
			if (willZipFile.isDirectory()) {
				dirToZip2(willZipPath, willZipFile, zos);
			}
			//           
			zos.close();
		} catch (Exception e) {
			// TODO: handle exception
		}
	}
	
	
	/**
	 * @param willZipFilePath          
	 * @param zos                     
	 * 1         
	 * ZipEntry entry = new ZipEntry();
	 * zos.putNextEntry(entry);
	 *     ZipEntry          
	 *                  ZipEntry   
	 * 
	 * 2 fis.close()       zos.close()
	 *    zos          .           
	 *       zos .     ,           
	 *    
	 */
	public void fileToZip2(String willZipFilePath,ZipOutputStream zos){
		try {
			File willZipFile=new File(willZipFilePath);
			ZipEntry entry = new ZipEntry(getEntryName2(willZipFilePath, willZipFile));
			zos.putNextEntry(entry);
			FileInputStream fis = new FileInputStream(willZipFilePath);
			int len = 0;
			while ((len = fis.read()) != -1){
				zos.write(len);
			}
			fis.close();
			//     !
			//zos.close();
		} catch (Exception e) {
		}
	}
	
	/**
	 * @param willZipDirctoryPath          
	 * @param willZipedDirectory       
	 * @param zos                      
	 *   :
	 *           
	 * getEntryName2(willZipDirctoryPath, willZipedDirectory)+"/"
	 *   "/"      
	 */
	public void dirToZip2(String willZipDirctoryPath,File willZipedDirectory, ZipOutputStream zos) {
			if (willZipedDirectory.isDirectory()) {
				File[] files = willZipedDirectory.listFiles();
				//         
	            if (files.length==0) {
					ZipEntry zipEntry=new ZipEntry
					(getEntryName2(willZipDirctoryPath, willZipedDirectory)+"/");
					try {
						zos.putNextEntry(zipEntry);
					} catch (Exception e) {
						e.printStackTrace();
					}
					return;
				}
	            for (int i = 0; i < files.length; i++) {
					File file = files[i];
					//    ,    fileToZip()
					if (file.isFile()) {
						fileToZip2(file.getAbsolutePath(), zos);
					}
					//    ,    dirToZip()
					if (file.isDirectory()) {
						dirToZip2(file.getAbsolutePath(),file, zos);
					}
				}
			}
		}
	
	
	/**
	 * @param rawPath                  
	 * @param file                
	 * @return         entryName
	 * 
	 *      EntryName,              (  )
	 *      
	 *   :
	 * 1              , E:\  rawPath.substring(3);
	 * 2    "@param file            ".         
	 *      ,         ,         . 
	 */
	public String getEntryName2(String rawPath,File file){
		try {
			String rawDir=rawPath.substring(3);
			int rawDirIndex=file.getAbsolutePath().indexOf(rawDir);
			String entryName=file.getAbsolutePath().substring(rawDirIndex);
			return entryName;
		} catch (Exception e) {
		}
		return null;
	}

	
	/**
	 * @param zipedFilePath          
	 * @param unzipPath              
	 *               :
	 * 1          file.mkdir(s)()   
	 *           .  :
	 *  File f=new File("F:\\test\\x.txt");
		if (!f.exists()) {
				f.createNewFile();
		}
		      ,  x.txt         !!
		       :
		File f=new File("F:\\test\\x.txt");
		f.getParentFile().mkdirs();
		if (!f.exists()) {
				f.createNewFile();
		}
		2     
		File f=new File("F:\\test\\x.txt");
		if (f.isFile()) {
			System.out.println("true");
		}else{
			System.out.println("false");
		}
		   false
		3     
		File f=new File("F:\\x.txt");
		if (f.isFile()) {
			System.out.println("true");
		}else{
			System.out.println("false");
		}
		   false
		    new   File,     !!!
		File f=new File("F:\\x.txt");
		f.createNewFile();
		if (f.isFile()) {
			System.out.println("true");
		}else{
			System.out.println("false");
		}
		   true
		
		  :
		if (zipEntry.isDirectory()) {
		    new File(perUnzipFilePath).mkdirs();
		} else {
			new File(perUnzipFilePath).getParentFile().mkdirs();
		}
		          .
		                      .
		        ,        ,    
		else {
				fos = new FileOutputStream(perUnzipFile);
				is = zipFile.getInputStream(zipEntry);
				while ((len = is.read(buffer)) != -1) {
					fos.write(buffer, 0, len);
				}
			}
		   if(perUnzipFile.isFile()){}   ,     .
		   perUnzipFile    perUnzipFile.createNewFile();
		      File.     ,           .
		       File     :
		1 File f=new File("");
		  f.createNewFile();
		        f  
		2 file f=new File("");
		                 
		       :
		  File f=new File("F:\\2221x.txt");
	      FileOutputStream fos=new FileOutputStream(f);
		  String string="hello";
		  byte []b=string.getBytes();
		  fos.write(b, 0, b.length);		
		            .
		       :     f.createNewFile()      .     
		  FileOutputStream           .
			       :
			File f=new File("F:\\2221x.txt");
			if (f.isFile()) {
				System.out.println("true1");
			} else {
				System.out.println("false1");
			}
			FileOutputStream fos=new FileOutputStream(f);
			if (f.isFile()) {
				System.out.println("true2");
			} else {
				System.out.println("false2");
			}
			String string="hello";
			byte []b=string.getBytes();
			fos.write(b, 0, b.length);
			  false1,true2
			       .
		
	 */
	public void unZipFile2(String zipedFilePath, String unzipPath) {
		FileOutputStream fos=null;
		InputStream is=null;
		ZipEntry zipEntry=null;
		String perUnzipFilePath=null;
		if (!unzipPath.endsWith(File.separator)) {
			unzipPath+=File.separator;
		}
		try {
			ZipFile zipFile=new ZipFile(zipedFilePath);
			Enumeration entries=zipFile.entries();
			byte [] buffer=new byte[1024*8];
			int len=0;
			while (entries.hasMoreElements()) {
				zipEntry = (ZipEntry) entries.nextElement();
				perUnzipFilePath = unzipPath + zipEntry.getName();
				//1       
				if (zipEntry.isDirectory()) {
					//         
					//     
					new File(perUnzipFilePath).mkdirs();
				} else {
					//            
					new File(perUnzipFilePath).getParentFile().mkdirs();
				}
                //2                
				// 2.1if               .  if      
				//    ,     .
				// 2.2else                     
				File perUnzipFile = new File(perUnzipFilePath);
				if (perUnzipFile.isDirectory()) {
					File[] files = perUnzipFile.listFiles();
					for (int i = 0; i < files.length; i++) {
						File file = files[i];
						fos = new FileOutputStream(file);
						is = zipFile.getInputStream(zipEntry);
						while ((len = is.read(buffer)) != -1) {
							fos.write(buffer, 0, len);
						}
					}
				} else {
					fos = new FileOutputStream(perUnzipFile);
					is = zipFile.getInputStream(zipEntry);
					while ((len = is.read(buffer)) != -1) {
						fos.write(buffer, 0, len);
					}
				}
			}
			if (fos!=null) {
				fos.close();
			}
			if (is!=null) {
				is.close();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}

좋은 웹페이지 즐겨찾기