2016-11-28 179 views
1

我的應用程序必須下載一個zip文件,並且必須將其解壓縮到應用程序文件夾中。問題是,zip沒有文件,但文件夾中,並在每個文件夾中有不同的文件。我會保持相同的結構,但我不知道它是如何做到的。我成功了,如果我用一個文件的zip文件,但沒有一個文件夾的zip文件。有人知道它是怎麼做到的? 非常感謝。從android中提取壓縮文件夾

+0

https://github.com/commonsguy/cwac-security/#usage-ziputils – CommonsWare

回答

3

您將需要爲ZIP存檔中的每個目錄條目創建目錄。這是我寫的一個方法和用途,將讓目錄結構:

/** 
* Unzip a ZIP file, keeping the directory structure. 
* 
* @param zipFile 
*  A valid ZIP file. 
* @param destinationDir 
*  The destination directory. It will be created if it doesn't exist. 
* @return {@code true} if the ZIP file was successfully decompressed. 
*/ 
public static boolean unzip(File zipFile, File destinationDir) { 
    ZipFile zip = null; 
    try { 
    destinationDir.mkdirs(); 
    zip = new ZipFile(zipFile); 
    Enumeration<? extends ZipEntry> zipFileEntries = zip.entries(); 
    while (zipFileEntries.hasMoreElements()) { 
     ZipEntry entry = zipFileEntries.nextElement(); 
     String entryName = entry.getName(); 
     File destFile = new File(destinationDir, entryName); 
     File destinationParent = destFile.getParentFile(); 
     if (destinationParent != null && !destinationParent.exists()) { 
     destinationParent.mkdirs(); 
     } 
     if (!entry.isDirectory()) { 
     BufferedInputStream is = new BufferedInputStream(zip.getInputStream(entry)); 
     int currentByte; 
     byte data[] = new byte[DEFUALT_BUFFER]; 
     FileOutputStream fos = new FileOutputStream(destFile); 
     BufferedOutputStream dest = new BufferedOutputStream(fos, DEFUALT_BUFFER); 
     while ((currentByte = is.read(data, 0, DEFUALT_BUFFER)) != EOF) { 
      dest.write(data, 0, currentByte); 
     } 
     dest.flush(); 
     dest.close(); 
     is.close(); 
     } 
    } 
    } catch (Exception e) { 
    return false; 
    } finally { 
    if (zip != null) { 
     try { 
     zip.close(); 
     } catch (IOException ignored) { 
     } 
    } 
    } 
    return true; 
} 
+0

好工作。拯救我。 – Abhishek