簡體   English   中英

在Android中下載zip文件

[英]Downloading zip file in android

我有以下代碼片段,可從Internet將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);
}

你能告訴我我在做什么錯嗎?

嘗試使用以下代碼下載文件:

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

看起來您在保存期間破壞了zip文件:

代替:

outStream.write(data, 0, bytesRead);

嘗試:

outStream.write(data);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM