从url下载zip文件的程序,并在android中提取适当的目录结构

时间:2014-08-23 12:08:03

标签: android

您好建议我从url下载zip文件的程序,并在android中提取与正确的目录结构。 其实我已为此编写代码但此程序不维护文件夹结构。 将所有文件解压缩到指定的目标目录中。 请建议。

  public class AndroidQAActivity extends Activity {
      EditText eText;
      private static Random random = new Random(Calendar.getInstance().getTimeInMillis());
      private ProgressDialog mProgressDialog;
        String unzipLocation = Environment.getExternalStorageDirectory() + "/test.zip/";
        String zipFile =Environment.getExternalStorageDirectory() + "/test.zip";
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
   // setContentView(R.layout.main);
    DownloadMapAsync mew = new DownloadMapAsync();
    mew.execute("http://alphapluss.ecotechservices.com/Downloads/10228.zip");

  }


class DownloadMapAsync extends AsyncTask<String, String, String> {
       String result ="";
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        mProgressDialog = new ProgressDialog(AndroidQAActivity.this);
        mProgressDialog.setMessage("Downloading Zip File..");
        mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        mProgressDialog.setCancelable(false);
        mProgressDialog.show();


    }

    @Override
    protected String doInBackground(String... aurl) {
        int count;

    try {


    URL url = new URL(aurl[0]);
    URLConnection conexion = url.openConnection();
    conexion.connect();
    int lenghtOfFile = conexion.getContentLength();
    InputStream input = new BufferedInputStream(url.openStream());

    OutputStream output = new FileOutputStream(zipFile);

    byte data[] = new byte[1024];
    long total = 0;

        while ((count = input.read(data)) != -1) {
            total += count;
            publishProgress(""+(int)((total*100)/lenghtOfFile));
            output.write(data, 0, count);
        }
        output.close();
        input.close();
        result = "true";

    } catch (Exception e) {

        result = "false";
    }
    return null;

    }
    protected void onProgressUpdate(String... progress) {
         Log.d("ANDRO_ASYNC",progress[0]);
         mProgressDialog.setProgress(Integer.parseInt(progress[0]));
    }

    @Override
    protected void onPostExecute(String unused) {
        mProgressDialog.dismiss();
        if(result.equalsIgnoreCase("true")){
        try {
            unzip();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        }
        else{

        }
    }
}



  public void unzip() throws IOException {
        mProgressDialog = new ProgressDialog(AndroidQAActivity.this);
        mProgressDialog.setMessage("Please Wait...Extracting zip file ... ");
        mProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        mProgressDialog.setCancelable(false);
        mProgressDialog.show();
        new UnZipTask().execute(zipFile, unzipLocation);
         }




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);
          }


            UnzipUtil d = new UnzipUtil(zipFile, unzipLocation); 
            d.unzip();

      } catch (Exception e) {

          return false;
      }

      return true;
  }

  @Override
  protected void onPostExecute(Boolean result) {
      mProgressDialog.dismiss();

  }


  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("", "Extracting: " + entry);
      BufferedInputStream inputStream = new BufferedInputStream(zipfile.getInputStream(entry));
      BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(outputFile));

      try {

      } finally {
        outputStream.flush();
        outputStream.close();
        inputStream.close();


      }
  }

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


}



       **And this is my UnzipUtil Class**

       public class UnzipUtil { 
  private String _zipFile; 
  private String _location; 

  public UnzipUtil(String zipFile, String location) { 
    _zipFile = zipFile; 
    _location = location; 

    _dirChecker(""); 
  } 

  public void unzip() { 
    try  { 
      FileInputStream fin = new FileInputStream(_zipFile); 
      ZipInputStream zin = new ZipInputStream(fin); 
      ZipEntry ze = null; 
      while ((ze = zin.getNextEntry()) != null) { 
        Log.v("Decompress", "Unzipping " + ze.getName()); 

        if(ze.isDirectory()) { 
          _dirChecker(ze.getName()); 
        } else { 
          FileOutputStream fout = new FileOutputStream(_location + ze.getName()); 
       //   for (int c = zin.read(); c != -1; c = zin.read()) { 
         //   fout.write(c); 


            byte[] buffer = new byte[8192];
             int len;
             while ((len = zin.read(buffer)) != -1) {
                 fout.write(buffer, 0, len);
             }
             fout.close();

        //  } 

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

      } 
      zin.close(); 
    } catch(Exception e) { 
      Log.e("Decompress", "unzip", e); 
    } 

  } 

  private void _dirChecker(String dir) { 
    File f = new File(_location + dir); 

    if(!f.isDirectory()) { 
      f.mkdirs(); 
    } 
  } 
}

1 个答案:

答案 0 :(得分:1)

我首先要与你共享一些url你想要下载文件,如下面的stackoverflow链接所示

Download a file programatically on Android然后从zip中提取文件,如以下链接所示Android Unzipping files Programmatically in android

相关问题