2017-05-01 42 views
0

我正在將zip文件從服務器下載到內部存儲器。下載後,我想在內部存儲本身解壓該文件。我的文件被下載到內部存儲器,我可以看到,但解壓縮時,我無法讀取它。下面是我的unzipfile()方法。任何人都可以告訴我哪裏出錯了?Android從內部存儲器解壓縮zip文件

public void unzipfile() 
    { 
     try { 

      Log.d("unzipiing","unzipping"); 
      ContextWrapper cw = new ContextWrapper(context); 
      String name_="foldername"; //Folder name in device android/data/ 
      File directory = cw.getDir(name_, Context.MODE_PRIVATE); 
      File mypath=new File(directory,"dwnld"); 

      FileOutputStream fout = new FileOutputStream(mypath); 

      File yourFile = new File(directory,"dwnld.zip"); 
      Log.d("unzipiing","filepath -" + yourFile.getPath()); 

      FileInputStream fin = new FileInputStream(yourFile.getPath()); 
      ZipInputStream zin = new ZipInputStream(fin); 
      Log.d("unzipiing","zin size -" + zin.available()); 
      // zin.available() give -1 in console log 

      BufferedInputStream in = new BufferedInputStream(zin); 
      BufferedOutputStream out = new BufferedOutputStream(fout); 


     byte b[] = new byte[zin.available()]; 
     int n; 
      Log.d("unzip","n - " + in.read(b,0,1024)); 
     while ((n = in.read(b,0,1024)) >= 0) { 
      out.write(b,0,n); 
      Log.d("unzip byte"," - " + n); 
     } 

     out.flush(); 
     out.close(); 
      in.close(); 
      fin.close(); 
      zin.close(); 
     } 
     catch (Exception e){ 
     } 
    } 
+0

到底在哪問題尚不清楚。你可以嘗試替代解決方案來完成它:http://stackoverflow.com/questions/3382996/how-to-unzip-files-programmatically-in-android –

+0

感謝您的鏈接和幫助。將嘗試該解決方案。但是我想知道爲什麼這個代碼不工作:-( –

+0

)你可以在一段時間內對你的代碼發表評論,繼續下一組解決方案,當你獲得免費的代碼時嘗試調試你的代碼 –

回答

0
<uses-permission android:name="android.permission.WRITE_INTERNAL_STORAGE" /> 
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/> 

使用這種方法解壓

public void unzip(String _zipFile, String _targetLocation) { 

      //create target location folder if not exist 
      dirChecker(_targetLocatioan); 

      try { 
       FileInputStream fin = new FileInputStream(_zipFile); 
       ZipInputStream zin = new ZipInputStream(fin); 
       ZipEntry ze = null; 
       while ((ze = zin.getNextEntry()) != null) { 

        //create dir if required while unzipping 
        if (ze.isDirectory()) { 
         dirChecker(ze.getName()); 
        } else { 
         FileOutputStream fout = new FileOutputStream(_targetLocation + ze.getName()); 
         for (int c = zin.read(); c != -1; c = zin.read()) { 
          fout.write(c); 
         } 

         zin.closeEntry(); 
         fout.close(); 
        } 

       } 
       zin.close(); 
      } catch (Exception e) { 
       System.out.println(e); 
      } 
    } 

檢查路徑

public void dirChecker(String filepath) 
{ 
File file = new File(filePath); 
if(file.exists())  
//Do something 
else 
// Do something else. 
}