2011-02-17 6 views

답변

15
static Handler myHandler; 
ProgressDialog myProgress; 

public void unzipFile(File zipfile) { 
     myProgress = ProgressDialog.show(getContext(), "Extract Zip", 
         "Extracting Files...", true, false); 
     File zipFile = zipfile; 
     String directory = null; 
     directory = zipFile.getParent(); 
     directory = directory + "/"; 
     myHandler = new Handler() { 

       @Override 
       public void handleMessage(Message msg) { 
         // process incoming messages here 
         switch (msg.what) { 
         case 0: 
           // update progress bar 
           myProgress.setMessage("" + (String) msg.obj); 
           break; 
         case 1: 
           myProgress.cancel(); 
           Toast toast = Toast.makeText(getContext(), 
               "Zip extracted successfully", 
Toast.LENGTH_SHORT); 
           toast.show(); 
           provider.refresh(); 
           break; 
         case 2: 
           myProgress.cancel(); 
           break; 
         } 
         super.handleMessage(msg); 
       } 

     }; 
     Thread workthread = new Thread(new UnZip(zipFile, directory)); 
     workthread.start(); 
} 

public class UnZip implements Runnable { 

     File archive; 
     String outputDir; 

     public UnZip(File ziparchive, String directory) { 
       archive = ziparchive; 
       outputDir = directory; 
     } 

     public void log(String log) { 
       Log.v("unzip", log); 
     } 

     @SuppressWarnings("unchecked") 
     public void run() { 
       Message msg; 
       try { 
         ZipFile zipfile = new ZipFile(archive); 
         for (Enumeration e = zipfile.entries(); 
e.hasMoreElements();) { 
           ZipEntry entry = (ZipEntry) e.nextElement(); 
           msg = new Message(); 
           msg.what = 0; 
           msg.obj = "Extracting " + entry.getName(); 
           myHandler.sendMessage(msg); 
           unzipEntry(zipfile, entry, outputDir); 
         } 
       } catch (Exception e) { 
         log("Error while extracting file " + archive); 
       } 
       msg = new Message(); 
       msg.what = 1; 
       myHandler.sendMessage(msg); 
     } 

     @SuppressWarnings("unchecked") 
     public void unzipArchive(File archive, String outputDir) { 
       try { 
         ZipFile zipfile = new ZipFile(archive); 
         for (Enumeration e = zipfile.entries(); 
e.hasMoreElements();) { 
           ZipEntry entry = (ZipEntry) e.nextElement(); 
           unzipEntry(zipfile, entry, outputDir); 
         } 
       } catch (Exception e) { 
         log("Error while extracting file " + archive); 
       } 
     } 

     private void unzipEntry(ZipFile zipfile, ZipEntry entry, 
         String outputDir) throws IOException { 

       if (entry.isDirectory()) { 
         createDir(new File(outputDir, entry.getName())); 
         return; 
       } 

       File outputFile = new File(outputDir, entry.getName()); 
       if (!outputFile.getParentFile().exists()) { 
         createDir(outputFile.getParentFile()); 
       } 

       log("Extracting: " + entry); 
       BufferedInputStream inputStream = new 
BufferedInputStream(zipfile 
           .getInputStream(entry)); 
       BufferedOutputStream outputStream = new BufferedOutputStream(
           new FileOutputStream(outputFile)); 

       try { 
         IOUtils.copy(inputStream, outputStream); 
       } finally { 
         outputStream.close(); 
         inputStream.close(); 
       } 
     } 

     private void createDir(File dir) { 
       log("Creating dir " + dir.getName()); 
       if (!dir.mkdirs()) 
         throw new RuntimeException("Can not create dir " + dir); 
     } 
} 

이 내가 AsyncTask를 확장하고 주 스레드에서 관찰자를 업데이트 할 수 있습니다 초보자 방법의 수정 된 버전을 사용하고 덕분에 사람들에게 나를 위해

+0

handleMessage()의 case 2는 무엇입니까? 나는 어떤 msg.what = 2를 볼 수 없다. 나를 위해 작동 – Turnsole

+0

하지만, 내가 서버에서 압축 파일을 누른 다음 압축을 풉니 다, 그것은 나를 보여줍니다 java.util.zip.ZipException 오류 : EOCD 찾을 수 없다 그것에 대한 어떤 생각 이건 –

37

을 일 것입니다. Byte Byte 압축은 매우 느리며 피해야합니다. 대신에 더 효율적인 방법은 많은 양의 데이터를 출력 스트림에 복사하는 것입니다.

private void unzipWebFile(String filename) { 
    String unzipLocation = getExternalFilesDir(null) + "/unzipped"; 
    String filePath = Environment.getExternalStorageDirectory().toString(); 

    UnZipper unzipper = new UnZipper(filename, filePath, unzipLocation); 
    unzipper.addObserver(this); 
    unzipper.unzip(); 
} 

귀하의 관찰자가 update(Observable observable, Object data) 콜백 압축 해제 완료를 얻을 것이다 :

package com.blarg.webviewscroller; 

import java.io.BufferedInputStream; 
import java.io.BufferedOutputStream; 
import java.io.File; 
import java.io.FileOutputStream; 
import java.io.IOException; 
import java.util.Enumeration; 
import java.util.Observable; 
import java.util.zip.ZipEntry; 
import java.util.zip.ZipFile; 

import org.apache.commons.io.IOUtils; 

import android.os.AsyncTask; 
import android.util.Log; 

public class UnZipper extends Observable { 

    private static final String TAG = "UnZip"; 
    private String mFileName, mFilePath, mDestinationPath; 

    public UnZipper (String fileName, String filePath, String destinationPath) { 
     mFileName = fileName; 
     mFilePath = filePath; 
     mDestinationPath = destinationPath; 
    } 

    public String getFileName() { 
     return mFileName; 
    } 

    public String getFilePath() { 
     return mFilePath; 
    } 

    public String getDestinationPath() { 
     return mDestinationPath; 
    } 

    public void unzip() { 
     String fullPath = mFilePath + "/" + mFileName + ".zip"; 
     Log.d(TAG, "unzipping " + mFileName + " to " + mDestinationPath); 
     new UnZipTask().execute(fullPath, mDestinationPath); 
    } 

    private class UnZipTask extends AsyncTask<String, Void, Boolean> { 

     @SuppressWarnings("rawtypes") 
     @Override 
     protected Boolean doInBackground(String... params) { 
      String filePath = params[0]; 
      String destinationPath = params[1]; 

      File archive = new File(filePath); 
      try { 
       ZipFile zipfile = new ZipFile(archive); 
       for (Enumeration e = zipfile.entries(); e.hasMoreElements();) { 
        ZipEntry entry = (ZipEntry) e.nextElement(); 
        unzipEntry(zipfile, entry, destinationPath); 
       } 
      } catch (Exception e) { 
       Log.e(TAG, "Error while extracting file " + archive, e); 
       return false; 
      } 

      return true; 
     } 

     @Override 
     protected void onPostExecute(Boolean result) { 
      setChanged(); 
      notifyObservers(); 
     } 

     private void unzipEntry(ZipFile zipfile, ZipEntry entry, 
       String outputDir) throws IOException { 

      if (entry.isDirectory()) { 
       createDir(new File(outputDir, entry.getName())); 
       return; 
      } 

      File outputFile = new File(outputDir, entry.getName()); 
      if (!outputFile.getParentFile().exists()) { 
       createDir(outputFile.getParentFile()); 
      } 

      Log.v(TAG, "Extracting: " + entry); 
      BufferedInputStream inputStream = new BufferedInputStream(zipfile.getInputStream(entry)); 
      BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(outputFile)); 

      try { 
       IOUtils.copy(inputStream, outputStream); 
      } finally { 
       outputStream.close(); 
       inputStream.close(); 
      } 
     } 

     private void createDir(File dir) { 
      if (dir.exists()) { 
       return; 
      } 
      Log.v(TAG, "Creating dir " + dir.getName()); 
      if (!dir.mkdirs()) { 
       throw new RuntimeException("Can not create dir " + dir); 
      } 
     } 
    } 
} 

그것은이 같은 Observer를 구현하는 클래스에 의해 사용됩니다. 때때로 당신이 그것을 압축 해제 후 파일을 삭제하려면 원하는 파일이 있다면 예외를 throw 때문에, 파일을 닫아야합니다 doInBackground()에서

ZipEtries을 반복 한 후 : 대답 rich.e @에 대한

+0

이것은 받아 들여진 대답이어야합니다. – Prateek

+0

IOUtils를 구할 수있는 곳과 설치 방법은 무엇입니까? –

+0

IOUtils는 Apache Commons IO https://commons.apache.org/proper/commons-io/의 일부입니다. –

2

은 "부가 기능" 폐쇄되지 않음 :

try { 
     ZipFile zipfile = new ZipFile(archive); 
     int entries = zipfile.size(); 
     int total = 0; 
     if(onZipListener != null) 
      onZipListener.onUncompressStart(archive); 

     for (Enumeration<?> e = zipfile.entries(); e.hasMoreElements();) { 
      ZipEntry entry = (ZipEntry) e.nextElement(); 
      if(onZipListener != null) 
       onZipListener.onUncompressProgress(archive, (int) (total++ * 100/entries)); 
      unzipEntry(zipfile, entry, path); 
     } 
     zipfile.close(); 
    } catch (Exception e) { 
     e.printStackTrace(); 
    } 
관련 문제