【问题标题】:Downloading zip file in android在android中下载zip文件
【发布时间】:2015-07-21 16:27:30
【问题描述】:

我有以下代码 sn-p 从互联网下载一个 zip 文件到我的 SD 卡。它以原始大小下载文件。但我无法提取文件,因为它显示“文件损坏”错误。所有网址都会发生这种情况。

URL url;
URLConnection conn;
int fileSize;
InputStream inStream;
String outFile;
String fileName = "";
OutputStream outStream;
Message msg;
msg = Message.obtain(mhandler, DOWNLOAD_STARTED, 0, 0, downloadUrl);
mhandler.sendMessage(msg);
try {
    url = new URL(downloadUrl);
    conn = url.openConnection();
    if(url.getProtocol().equals("https")){
        conn = (HttpsURLConnection) conn;

    }
    conn.addRequestProperty("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
    conn.addRequestProperty("Accept-Encoding", "gzip, deflate, sdch");
    fileSize = conn.getContentLength();
    int fileSizeKB = fileSize / 1024;
    msg = Message.obtain(mhandler, DOWNLOAD_STARTED, fileSizeKB, 0,
            fileName);
    mhandler.sendMessage(msg);
    inStream = conn.getInputStream();
    outFile = Environment.getDataDirectory().getPath()+"/windows/Documents/file.zip";
    outStream = new FileOutputStream(outFile);
    byte[] data = new byte[1024];
    int bytesRead = 0;
    while (!isInterrupted()
            && (bytesRead = inStream.read(data)) != -1) {
        outStream.write(data, 0, bytesRead);
    }
    outStream.flush();
    outStream.close();
    inStream.close();
    if (isInterrupted()) {
        new File(outFile).delete();
    } else {
        msg = Message.obtain(mhandler, DOWNLOAD_COMPLETED);
        mhandler.sendMessage(msg);
    }
} catch (Exception exp) {
    msg = Message.obtain(mhandler, DOWNLOAD_FAILED);
    mhandler.sendMessage(msg);
}

你能告诉我我做错了什么吗?

【问题讨论】:

标签: java android httpurlconnection


【解决方案1】:

试试这个代码来下载文件:

public class download extends Activity {

public static final int DIALOG_DOWNLOAD_PROGRESS = 0;
private Button startBtn;
private ProgressDialog mProgressDialog;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    startBtn = (Button)findViewById(R.id.startBtn);
    startBtn.setOnClickListener(new OnClickListener(){
        public void onClick(View v) {
            startDownload();
        }
    });
}

private void startDownload() {
    String url = "http://farm1.static.flickr.com/114/298125983_0e4bf66782_b.zip";
    new DownloadFileAsync().execute(url);
}
@Override
protected Dialog onCreateDialog(int id) {
    switch (id) {
    case DIALOG_DOWNLOAD_PROGRESS:
        mProgressDialog = new ProgressDialog(this);
        mProgressDialog.setMessage("Downloading file..");
        mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        mProgressDialog.setCancelable(false);
        mProgressDialog.show();
        return mProgressDialog;
    default:
        return null;
    }
}

class DownloadFileAsync extends AsyncTask<String, String, String> {

@Override
protected void onPreExecute() {
    super.onPreExecute();
    showDialog(DIALOG_DOWNLOAD_PROGRESS);
}

@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();
Log.d("ANDRO_ASYNC", "Lenght of file: " + lenghtOfFile);

InputStream input = new BufferedInputStream(url.openStream());
OutputStream output = new FileOutputStream("/sdcard/some_photo_from_gdansk_poland.zip");

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.flush();
    output.close();
    input.close();
} catch (Exception e) {}
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) {
    dismissDialog(DIALOG_DOWNLOAD_PROGRESS);
}
}
}

【讨论】:

    【解决方案2】:
    int mFileSize = 0;
    String path = "/sdcard/path";
    final int BUFFER_SIZE = 1024;
    BufferedInputStream bis;
    RandomAccessFile fos;
    byte[] buf = new byte[BUFFER_SIZE];
    int curPosition = 0;
    File destFile = new File(path + File.separator + "fileName");
    if(destFile.exists()) {
        destFile.delete();
    }
    try {
        URL url = new URL("http://xxx.xxx");
        URLConnection conn = url.openConnection();
        conn.setAllowUserInteraction(true);
        mFileSize = conn.getContentLength();
        if(mFileSize <= 0) {
            if(destFile.exists()) {
                destFile.delete();
            }
            return;
        }           
        fos = new RandomAccessFile(destFile, "rw");
        bis = new BufferedInputStream(conn.getInputStream());            
        while(curPosition < mFileSize) {               
            int len = bis.read(buf, 0, BUFFER_SIZE);
            if (len == -1) {
                break;
            }
            fos.write(buf, 0, len);
            curPosition += len;
        }
        bis.close();
        fos.close();
    } catch (Exception e) {
        e.printStackTrace();
        if(destFile.exists()) {
            destFile.delete();
        }
    }
    

    【讨论】:

      【解决方案3】:

      看起来你在保存过程中破坏了你的 zip 文件:

      代替:

      outStream.write(data, 0, bytesRead);
      

      尝试:

      outStream.write(data);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-07-07
        • 2015-08-28
        • 1970-01-01
        • 1970-01-01
        • 2012-03-08
        • 1970-01-01
        相关资源
        最近更新 更多