2012-11-15 96 views
2

我正在做一個簡單的android應用程序,它由壓縮文件夾組成。實際上壓縮過程已完成,文件保存在已定義的位置。但問題是,當我從模擬器中壓縮壓縮文件,並手動解壓縮文件損壞。有什麼問題。手動解壓縮時文件是否被破壞?android壓縮文件夾

我的文件夾結構如下

TestPlay1-給出包含兩個子目錄 - 播放列表和內容
目錄播放列表包含一個XML文件
目錄內容包含文件,如圖片和視頻

我下面

String zipFile = "/mnt/sdcard/Testplay1.zip"; 
byte[] buffer = new byte[1024]; 
FileOutputStream fos = null; 
try { 
    fos = new FileOutputStream(zipFile); 
} catch (FileNotFoundException e1) { 
    e1.printStackTrace(); 
} 
ZipOutputStream zos = new ZipOutputStream(fos); 
updata = new ArrayList<File>(); 
contentpath = new File(FOLDER_PATH); 
try { 
    if (contentpath.isDirectory()) { 
     File[] listFile = contentpath.listFiles(); 
     for (int i = 0; i < listFile.length; i++) { 
      if (listFile[i].isDirectory()) { 
       File[] contfile = listFile[i].listFiles(); 
       for (int j = 0; j < contfile.length; j++) { 
        updata.add(contfile[j]); 
        FileInputStream fis = new FileInputStream(contfile[j]); 
        zos.putNextEntry(new ZipEntry(contfile[j].getName())); 
        int length; 
        while ((length = fis.read(buffer)) > 0) { 
         zos.write(buffer, 0, length); 
        } 
        zos.closeEntry(); 
        // close the InputStream 
        fis.close(); 
       } 
      } 
     } 
     zos.close(); 
    } 
    System.out.println("Testplay1 Folder contains=>" + updata); 
} catch (Exception e) { 
    e.printStackTrace(); 
    // TODO: handle exception 
} 
+0

您應該考慮使用Apache的壓縮librairies完成。無需重新發明任何這些常見操作.. http://developer-tips.hubpages.com/hub/Zipping-and-Unzipping-Nested-Directories-in-Java-using-Apache-Commons-Compress – Snicolas

回答

3

代碼給我建議你使用Zip4j:http://www.lingala.net/zip4j/
這裏你可以把文件夾壓縮,其餘是由庫

ZipFile zipfile = new ZipFile("/mnt/sdcard/bla.zip"); 
ZipParameters parameters = new ZipParameters(); 
parameters.setCompressionMethod(Zip4jConstants.COMP_DEFLATE); 
parameters.setCompressionLevel(Zip4jConstants.DEFLATE_LEVEL_NORMAL); 
zipfile.addFolder("/mnt/sdcard/folderToZip", parameters); 
+0

謝謝爲您的答覆..你能告訴我的用法。我下載了用於eclipse工作空間的zip文件。那麼該如何處理這個zip文件? PLZ幫助我。 – Sunny

+0

解壓縮並將jar文件複製到Android項目的「libs」文件夾中 – Thommy