在Android中下载Zip文件返回Corrupt文件

时间:2014-04-15 04:32:51

标签: java android eclipse http

我正在尝试使用Java创建下载ZIP文件的应用程序,然后将其解压缩到Android设备上的“下载”文件夹中。问题是,当程序下载它时,ZIP文件下载已损坏且内部没有任何内容,当然,解压缩文件夹为空。我有三个主要类,分别是“下载文件”,“UnZip”,当然还有“MainActivity”。 他们在这里:

MainActivity:

package com.NautGames.xecta.app;

import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;
//Chat bot library
import org.alicebot.ab.Chat;
import org.alicebot.ab.Bot;
import android.widget.EditText;

import java.io.File;
import android.view.View;
import android.widget.Button;
import android.os.Environment;
import android.widget.TextView;
import android.widget.Toast;

import android.app.ProgressDialog;

public class MainActivity extends ActionBarActivity {

Button clickDownload;
TextView input;
String dPath = Environment.getExternalStorageDirectory().getPath() ;

private ProgressDialog mProgressDialog;

@Override
public void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    clickDownload = (Button)findViewById(R.id.btn_download);
}

//EditText mEdit = (EditText)findViewById(R.id.editText1);

public void buttonOnClick(View v)
{
    input = (TextView) findViewById(R.id.editText1);

    String dbPath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/Download/Ab";

    Button button=(Button) v;

    //Creating bot
    String botname="xecta";
    String path= dbPath;
    Bot xecta = new Bot(botname, path);

    Chat chatSession = new Chat(xecta);

    String request = input.getText().toString();
    String response = chatSession.multisentenceRespond(request);
    ((Button) v).setText(response);
}

/**
 * Button that starts download an Unzip.
 */
public void onClickDownload(View v)
{
    Button clickDownload = (Button) v;

    String dPath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/Download";

    ((Button) v).setText("Downloading");
    //To download zip
    //URL
    String url = "http://download1642.mediafire.com/hn64kc18pafg/ojajp9o26scdbwd/Files.zip";
    //Path to save to
    String savePath = dPath + "/Files";
    //Name to save as
    String saveName = "Xecta.zip";
    DownloadFile download = new DownloadFile();
    download.downloadFile(url, savePath, saveName);

    //To unzip files
    String zipFile = dPath + "/Files/files";
    String unzipLocation = dPath + "/Files";

    UnZip d = new UnZip(zipFile, unzipLocation);
    d.unzip();
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {

    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();
    if (id == R.id.action_settings) {
        return true;
    }
    return super.onOptionsItemSelected(item);
}
}

DownloadFile:

package com.NautGames.xecta.app;

import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.widget.Button;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;

public class DownloadFile extends ActionBarActivity{

Button download;

String FILE_DOWNLOAD_CONNECT = "Connecting...";
String FILE_DOWNLOAD_UPDATE = "Downloading";
String FILE_DOWNLOAD_COMPLETE = "Complete!";
String FILE_DOWNLOAD_ERROR = "Error Downloading";

@Override
public void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    download = (Button)findViewById(R.id.btn_download);
}

public void downloadFile(final String url, final String savePath, final String saveName) {
    new Thread(new Runnable() {
        public void run() {
            try {
                //download.setText(FILE_DOWNLOAD_CONNECT);
                URL sourceUrl = new URL(url);
                URLConnection conn = sourceUrl.openConnection();
                conn.connect();
                InputStream inputStream = conn.getInputStream();

                int fileSize = conn.getContentLength();

                File savefilepath = new File(savePath);
                if (!savefilepath.exists()) {
                    savefilepath.mkdirs();
                }
                File savefile = new File(savePath+saveName);
                if (savefile.exists()) {
                    savefile.delete();
                }
                savefile.createNewFile();

                FileOutputStream outputStream = new FileOutputStream(
                        savePath+saveName, true);

                byte[] buffer = new byte[1024];
                int readCount = 0;
                int readNum = 0;
                int prevPercent = 0;
                while (readCount < fileSize && readNum != -1) {
                    readNum = inputStream.read(buffer, 0, readNum);
                    if (readNum > -1) {
                        outputStream.write(buffer);

                        readCount = readCount + readNum;

                        int percent = (int) (readCount * 100 / fileSize);
                        if (percent > prevPercent) {
                            System.out.print(percent);

                            prevPercent = percent;
                        }
                    }
                }
                outputStream.flush();
                outputStream.close();
                inputStream.close();
                //Thread.sleep(50);
                //download.setText(FILE_DOWNLOAD_COMPLETE);

            } catch (Exception e) {
                //download.setText(FILE_DOWNLOAD_ERROR);
            }
        }
    }).start();
}
}

解压缩:

package com.NautGames.xecta.app;

import android.util.Log;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

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

public UnZip(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);
                }

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

BTW我正在运行Android Studio(预览版)0.4.6 在此先感谢。

更新仍无效,正在寻找答案。

更新立即开始工作。

1 个答案:

答案 0 :(得分:1)

这里的工作代码可以看..

MainActivity.java

import android.app.Activity;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class MainActivity extends Activity {

    private Button button;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        button=(Button)findViewById(R.id.button1);
        button.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub
                Utils.createDir(Environment.getExternalStorageDirectory().toString(),"Downloads");
                Utils.createDir(Environment.getExternalStorageDirectory().toString()+"/Downloads", "Files");

                String unzipLocation = Environment.getExternalStorageDirectory() +"/"+"Downloads"+"/"+"Files"+"/";
                String zipFile =Environment.getExternalStorageDirectory() +"/"+"Downloads"+"/"+"Files"+"."+"zip";
                String url="https://eventfo.com.au/index.php/userapi/api/eventdetaildownload/eventid/162/accesskey/534ccbcc10ab2/deviceId/85d2a504b2be7af4/deviceType/Android";
                try {
                    new Utils().downloadEventData(MainActivity.this,zipFile, unzipLocation, url);
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        });
    }
}

UnzipUtil.java

import android.util.Log; 
import java.io.File; 
import java.io.FileInputStream; 
import java.io.FileOutputStream; 
import java.util.zip.ZipEntry; 
import java.util.zip.ZipInputStream; 


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

Utils.java

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Color;
import android.os.AsyncTask;
import android.util.Log;
import android.view.Gravity;
import android.widget.TextView;
public class Utils
    {
            public static void createDir(String path,String dirName)
            {
                  String newFolder = "/"+dirName;
                  File myNewFolder = new File(path + newFolder);
                  myNewFolder.mkdir();
            }

            public void downloadEventData(Context context,String zipFile,String unzipLocation,String url) throws IOException
            {
                try {
                        new DownloadMapAsync(context,zipFile,unzipLocation).execute(url);
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
                private class DownloadMapAsync extends AsyncTask<String, String, String> {
                    String result ="";
                    Context context;
                    String zipFile;
                    String unzipLocation;
                    private ProgressDialog progressDialog;
                    String string;
                    public DownloadMapAsync(Context context,String zipFile,String unzipLocation) {
                        // TODO Auto-generated constructor stub
                        this.context=context;
                        this.zipFile=zipFile;
                        this.unzipLocation=unzipLocation;
                    }
                    @Override
                    protected void onPreExecute() {
                        super.onPreExecute();
                        progressDialog = new ProgressDialog(context);
                        progressDialog.setMessage("Downloading Zip File..");
                        progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
                        progressDialog.setCancelable(false);
                        progressDialog.show();
                    }

                    @Override
                    protected String doInBackground(String... aurl) {
                        int count;
                        HttpURLConnection http = null;
                    try {
                        URL url = new URL(aurl[0]);
                        if (url.getProtocol().toLowerCase().equals("https")) {
                            trustAllHosts();
                            HttpsURLConnection https = (HttpsURLConnection) url.openConnection();
                            https.setHostnameVerifier(DO_NOT_VERIFY);
                            http = https;
                        } else {
                            http = (HttpURLConnection) url.openConnection();
                        }
                    http.connect();
                    if (http.getResponseCode()==200)
                    {
                        int lenghtOfFile = http.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";
                    } 
                    else if (http.getResponseCode()==401)
                    {
                        result = "false";
                        string= "Download Limit exceed.";   
                    }  
                    else 
                    {
                        result = "false";
                        string=http.getResponseMessage();
                    }

                    } catch (Exception e) {
                        e.printStackTrace();
                        result = "false";
                        try {
                            if (http.getResponseCode()==401)
                            {
                                string= "Download Failed";  
                            } else {
                                string=e.toString();
                            }

                        } catch (IOException e1) {
                            // TODO Auto-generated catch block
                            e1.printStackTrace();
                        }
                    }
                    return result;

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

                    @Override
                    protected void onPostExecute(String unused) {
                        progressDialog.dismiss();
                        if(result.equalsIgnoreCase("true"))
                        {
                        try {
                            unzip(context,zipFile,unzipLocation);
                        } catch (IOException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                        }
                        else
                        {
                            customAlert(context, string);
                        }
                    }
                }
                @SuppressLint("NewApi")
                public void customAlert(Context context,String msgString)
                {
                    AlertDialog.Builder alertDialog2 = new AlertDialog.Builder(context,AlertDialog.THEME_DEVICE_DEFAULT_LIGHT);
                    TextView title = new TextView(context);
                    title.setText("Message");
                    title.setPadding(10, 10, 10, 10);
                    title.setGravity(Gravity.CENTER);
                    title.setTextColor(Color.BLACK);
                    title.setTextSize(20);
                    alertDialog2.setCustomTitle(title);
                    TextView msg = new TextView(context);
                    msg.setText(msgString);
                    msg.setPadding(10, 10, 10, 10);
                    msg.setGravity(Gravity.CENTER);
                    msg.setTextSize(18);
                    msg.setTextColor(Color.BLACK);
                    alertDialog2.setView(msg);
                    alertDialog2.setPositiveButton("OK",
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.cancel();
                            }
                        });
                    alertDialog2.show();
                }
                  public void unzip(Context context,String zipFile,String unzipLocation) throws IOException 
                  {
                        new UnZipTask(context,zipFile).execute(unzipLocation);
                  }

                private class UnZipTask extends AsyncTask<String, Void, Boolean> {
                    Context context;
                    String zipFile;
                    ProgressDialog progressDialog;

                 public UnZipTask(Context context,String zipFile) {
                    // TODO Auto-generated constructor stub
                     this.context=context;
                     this.zipFile=zipFile;
                    }
                  @Override
                    protected void onPreExecute() {
                        super.onPreExecute();
                        progressDialog = new ProgressDialog(context);
                        progressDialog.setMessage("Please Wait...Extracting zip file ... ");
                        progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
                        progressDialog.setCancelable(false);
                        progressDialog.show();

                    }
                  protected Boolean doInBackground(String... params) 
                  {
                      String filePath = zipFile;
                      String destinationPath = params[0];

                      File archive = new File(filePath);
                      try {


                         ZipFile zipfile = new ZipFile(archive);
                          for (@SuppressWarnings("rawtypes")
                        Enumeration e = zipfile.entries(); e.hasMoreElements();) {
                              ZipEntry entry = (ZipEntry) e.nextElement();
                              unzipEntry(zipfile, entry, destinationPath);
                          }


                            UnzipUtil d = new UnzipUtil(zipFile,params[0]); 
                            d.unzip();

                      } catch (Exception e) {
                          e.printStackTrace();
                          return false;
                      }

                      return true;
                  }

                  @Override
                  protected void onPostExecute(Boolean result)
                  {
                      progressDialog.dismiss();
                      File file=new File(zipFile);
                      file.delete();
                      customAlert(context,"Unzipping completed");
                  }

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

                      BufferedInputStream inputStream = new BufferedInputStream(zipfile.getInputStream(entry));
                      BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(outputFile));

                      try {

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


                      }
                  }

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

                  }

                 final static HostnameVerifier DO_NOT_VERIFY = new HostnameVerifier()
                 {
                        public boolean verify(String hostname, SSLSession session) {
                            return true;
                        }
                };
                private static void trustAllHosts() {
                    // Create a trust manager that does not validate certificate chains
                    TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
                        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                            return new java.security.cert.X509Certificate[] {};
                        }

                        public void checkClientTrusted(X509Certificate[] chain,
                                String authType) throws CertificateException {
                        }

                        public void checkServerTrusted(X509Certificate[] chain,
                                String authType) throws CertificateException {
                        }
                    } };

                    // Install the all-trusting trust manager
                    try {
                        SSLContext sc = SSLContext.getInstance("TLS");
                        sc.init(null, trustAllCerts, new java.security.SecureRandom());
                        HttpsURLConnection
                                .setDefaultSSLSocketFactory(sc.getSocketFactory());
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }   
}

的Manifest.xml

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.downloadzipunzip"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="18" />

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

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.example.downloadzipunzip.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

希望这段代码可以帮助你..