android壓縮解壓zip文件

網上各類方法的收集:java

一、上次寫了個解壓縮功能,但有侷限性,好比壓縮文件xx.zip 裏包括子目錄的狀況下,執行上次解壓縮的功能就不能實現咱們想要的效果,因而在網上參考了一下java的解壓縮功能。對上次解壓縮zip功能進行了修改。android

如今也能夠解壓 那些包含子目錄的zip文件。spa

/**
    * 解壓縮功能.
    * 將zipFile文件解壓到folderPath目錄下.
    * @throws Exception
*/
    public int upZipFile(File zipFile, String folderPath)throws ZipException,IOException {
    //public static void upZipFile() throws Exception{
        ZipFile zfile=new ZipFile(zipFile);
        Enumeration zList=zfile.entries();
        ZipEntry ze=null;
        byte[] buf=new byte[1024];
        while(zList.hasMoreElements()){
            ze=(ZipEntry)zList.nextElement();    
            if(ze.isDirectory()){
                Log.d("upZipFile", "ze.getName() = "+ze.getName());
                String dirstr = folderPath + ze.getName();
                //dirstr.trim();
                dirstr = new String(dirstr.getBytes("8859_1"), "GB2312");
                Log.d("upZipFile", "str = "+dirstr);
                File f=new File(dirstr);
                f.mkdir();
                continue;
            }
            Log.d("upZipFile", "ze.getName() = "+ze.getName());
            OutputStream os=new BufferedOutputStream(new FileOutputStream(getRealFileName(folderPath, ze.getName())));
            InputStream is=new BufferedInputStream(zfile.getInputStream(ze));
            int readLen=0;
            while ((readLen=is.read(buf, 0, 1024))!=-1) {
                os.write(buf, 0, readLen);
            }
            is.close();
            os.close();    
        }
        zfile.close();
        Log.d("upZipFile", "finishssssssssssssssssssss");
        return 0;
    }

    /**
    * 給定根目錄,返回一個相對路徑所對應的實際文件名.
    * @param baseDir 指定根目錄
    * @param absFileName 相對路徑名,來自於ZipEntry中的name
    * @return java.io.File 實際的文件
*/
    public static File getRealFileName(String baseDir, String absFileName){
        String[] dirs=absFileName.split("/");
        File ret=new File(baseDir);
        String substr = null;
        if(dirs.length>1){
            for (int i = 0; i < dirs.length-1;i++) {
                substr = dirs[i];
                try {
                    //substr.trim();
                    substr = new String(substr.getBytes("8859_1"), "GB2312");
                    
                } catch (UnsupportedEncodingException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                ret=new File(ret, substr);
                
            }
            Log.d("upZipFile", "1ret = "+ret);
            if(!ret.exists())
                ret.mkdirs();
            substr = dirs[dirs.length-1];
            try {
                //substr.trim();
                substr = new String(substr.getBytes("8859_1"), "GB2312");
                Log.d("upZipFile", "substr = "+substr);
            } catch (UnsupportedEncodingException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            
            ret=new File(ret, substr);
            Log.d("upZipFile", "2ret = "+ret);
            return ret;
        }
        return ret;
    }

 

記得要在AndroidManifest.xml裏添加權限:xml

 <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
 <uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>blog

 

二、我 們在平常生活中會用到解壓縮,這個是很是重要的,那麼咱們在android系統中有沒有解壓縮那。若是有的話,那咱們如何實現Zip文件的解壓縮功能呢? 那麼咱們就看看下面的解析吧,由於Android內部已經集成了zlib庫,對於英文和非密碼的Zip文件解壓縮仍是比較簡單的,下面給你們一個解壓縮 zip的java代碼,能夠在Android上任何版本中使用,Unzip這個靜態方法比較簡單,參數一爲源zip文件的完整路徑,參數二爲解壓縮後存放 的文件夾。但願這段代碼能教會你們解壓縮。ip

 

private static void Unzip(String zipFile, String targetDir) {
int BUFFER = 4096; //這裏緩衝區咱們使用4KB,
String strEntry; //保存每一個zip的條目名稱

try {
BufferedOutputStream dest = null; //緩衝輸出流
FileInputStream fis = new FileInputStream(zipFile);
ZipInputStream zis = new ZipInputStream(new BufferedInputStream(fis));
ZipEntry entry; //每一個zip條目的實例


while ((entry = zis.getNextEntry()) != null) {


try {
Log.i("Unzip: ","="+ entry);
int count; 
byte data[] = new byte[BUFFER];
strEntry = entry.getName();


File entryFile = new File(targetDir + strEntry);
File entryDir = new File(entryFile.getParent());
if (!entryDir.exists()) {
entryDir.mkdirs();
}


FileOutputStream fos = new FileOutputStream(entryFile);
dest = new BufferedOutputStream(fos, BUFFER);
while ((count = zis.read(data, 0, BUFFER)) != -1) {
dest.write(data, 0, count);
}
dest.flush();
dest.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
zis.close();
} catch (Exception cwj) {
cwj.printStackTrace();
}
}


上面是Android開發網總結的zip文件解壓縮代碼,但願你你們有用,須要注意的是參數均填寫完整的路徑,好比/mnt/sdcard/xxx.zip這樣的類型。


下面的方法是,解壓只有一個文件組成的zip到當前目錄,而且給解壓出的文件重命名:


public static void unzipSingleFileHereWithFileName(String zipPath, String name) throws IOException{
        File zipFile = new File(zipPath);
        File unzipFile = new File(zipFile.getParent() + "/" + name);
        ZipInputStream zipInStream = null;
        FileOutputStream unzipOutStream = null;
        try {
            zipInStream = new ZipInputStream(new FileInputStream(zipFile));
            ZipEntry zipEntry = zipInStream.getNextEntry();
            if (!zipEntry.isDirectory()) {
                unzipOutStream = new FileOutputStream(unzipFile);
                byte[] buf = new byte[4096];
                int len = -1;
                while((len = zipInStream.read(buf)) != -1){
                    unzipOutStream.write(buf, 0, len);
                }
            }
        } finally {
            if(unzipOutStream != null){
                unzipOutStream.close();
            }


            if (zipInStream != null) {
               zipInStream.close();
            }
        }
    }

 

 三、研究了一下Android上Zip的用法,寫了個類把經常使用的幾種方法寫了出來開發

/**
 * Android Zip壓縮解壓縮
 * @author Ren.xia
 * @version 1.0
 * @updated 26-七月-2010 13:04:27
 */
public class XZip {

	public XZip(){

	}
	
	/**
	 * 取得壓縮包中的 文件列表(文件夾,文件自選)
	 * @param zipFileString		壓縮包名字
	 * @param bContainFolder	是否包括 文件夾
	 * @param bContainFile		是否包括 文件
	 * @return
	 * @throws Exception
	 */
	public static java.util.List<java.io.File> GetFileList(String zipFileString, boolean bContainFolder, boolean bContainFile)throws Exception {
		
		android.util.Log.v("XZip", "GetFileList(String)");
		
		java.util.List<java.io.File> fileList = new java.util.ArrayList<java.io.File>();
		java.util.zip.ZipInputStream inZip = new java.util.zip.ZipInputStream(new java.io.FileInputStream(zipFileString));
		java.util.zip.ZipEntry zipEntry;
		String szName = "";
		
		while ((zipEntry = inZip.getNextEntry()) != null) {
			szName = zipEntry.getName();
		
			if (zipEntry.isDirectory()) {
		
				// get the folder name of the widget
				szName = szName.substring(0, szName.length() - 1);
				java.io.File folder = new java.io.File(szName);
				if (bContainFolder) {
					fileList.add(folder);
				}
		
			} else {
				java.io.File file = new java.io.File(szName);
				if (bContainFile) {
					fileList.add(file);
				}
			}
		}//end of while
		
		inZip.close();
		
		return fileList;
	}

	/**
	 * 返回壓縮包中的文件InputStream
	 * @param zipFileString		壓縮文件的名字
	 * @param fileString	解壓文件的名字
	 * @return InputStream
	 * @throws Exception
	 */
	public static java.io.InputStream UpZip(String zipFileString, String fileString)throws Exception {
		android.util.Log.v("XZip", "UpZip(String, String)");
		java.util.zip.ZipFile zipFile = new java.util.zip.ZipFile(zipFileString);
		java.util.zip.ZipEntry zipEntry = zipFile.getEntry(fileString);
		
		return zipFile.getInputStream(zipEntry);

	}
	
	
	/**
	 * 解壓一個壓縮文檔 到指定位置
	 * @param zipFileString	壓縮包的名字
	 * @param outPathString	指定的路徑
	 * @throws Exception
	 */
	public static void UnZipFolder(String zipFileString, String outPathString)throws Exception {
		android.util.Log.v("XZip", "UnZipFolder(String, String)");
		java.util.zip.ZipInputStream inZip = new java.util.zip.ZipInputStream(new java.io.FileInputStream(zipFileString));
		java.util.zip.ZipEntry zipEntry;
		String szName = "";
		
		while ((zipEntry = inZip.getNextEntry()) != null) {
			szName = zipEntry.getName();
		
			if (zipEntry.isDirectory()) {
		
				// get the folder name of the widget
				szName = szName.substring(0, szName.length() - 1);
				java.io.File folder = new java.io.File(outPathString + java.io.File.separator + szName);
				folder.mkdirs();
		
			} else {
		
				java.io.File file = new java.io.File(outPathString + java.io.File.separator + szName);
				file.createNewFile();
				// get the output stream of the file
				java.io.FileOutputStream out = new java.io.FileOutputStream(file);
				int len;
				byte[] buffer = new byte[1024];
				// read (len) bytes into buffer
				while ((len = inZip.read(buffer)) != -1) {
					// write (len) byte from buffer at the position 0
					out.write(buffer, 0, len);
					out.flush();
				}
				out.close();
			}
		}//end of while
		
		inZip.close();
	
	}//end of func
	

	/**
	 * 壓縮文件,文件夾
	 * @param srcFileString	要壓縮的文件/文件夾名字
	 * @param zipFileString	指定壓縮的目的和名字
	 * @throws Exception
	 */
	public static void ZipFolder(String srcFileString, String zipFileString)throws Exception {
		android.util.Log.v("XZip", "ZipFolder(String, String)");
		
		//建立Zip包
		java.util.zip.ZipOutputStream outZip = new java.util.zip.ZipOutputStream(new java.io.FileOutputStream(zipFileString));
		
		//打開要輸出的文件
		java.io.File file = new java.io.File(srcFileString);

		//壓縮
		ZipFiles(file.getParent()+java.io.File.separator, file.getName(), outZip);
		
		//完成,關閉
		outZip.finish();
		outZip.close();
	
	}//end of func
	
	/**
	 * 壓縮文件
	 * @param folderString
	 * @param fileString
	 * @param zipOutputSteam
	 * @throws Exception
	 */
	private static void ZipFiles(String folderString, String fileString, java.util.zip.ZipOutputStream zipOutputSteam)throws Exception{
		android.util.Log.v("XZip", "ZipFiles(String, String, ZipOutputStream)");
		
		if(zipOutputSteam == null)
			return;
		
		java.io.File file = new java.io.File(folderString+fileString);
		
		//判斷是否是文件
		if (file.isFile()) {

			java.util.zip.ZipEntry zipEntry =  new java.util.zip.ZipEntry(fileString);
			java.io.FileInputStream inputStream = new java.io.FileInputStream(file);
			zipOutputSteam.putNextEntry(zipEntry);
			
			int len;
			byte[] buffer = new byte[4096];
			
			while((len=inputStream.read(buffer)) != -1)
			{
				zipOutputSteam.write(buffer, 0, len);
			}
			
			zipOutputSteam.closeEntry();
		}
		else {
			
			//文件夾的方式,獲取文件夾下的子文件
			String fileList[] = file.list();
			
			//若是沒有子文件, 則添加進去便可
			if (fileList.length <= 0) {
				java.util.zip.ZipEntry zipEntry =  new java.util.zip.ZipEntry(fileString+java.io.File.separator);
				zipOutputSteam.putNextEntry(zipEntry);
				zipOutputSteam.closeEntry();				
			}
			
			//若是有子文件, 遍歷子文件
			for (int i = 0; i < fileList.length; i++) {
				ZipFiles(folderString, fileString+java.io.File.separator+fileList[i], zipOutputSteam);
			}//end of for
	
		}//end of if
		
	}//end of func
	
	public void finalize() throws Throwable {
		
	}

}
相關文章
相關標籤/搜索