0

I have following code snippet that downloads a zip file from internet to my SD card. It downloads the file with the original size. But I am unable to extract file as it shows "file corrupted" error. It happens with all the urls.

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

Can you please tell me what mistake am I doing?

injecteer
  • 20,038
  • 4
  • 45
  • 89
Rikesh Subedi
  • 1,755
  • 22
  • 21

3 Answers3

1

Try this code to download files :

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);
}
}
}
Karan
  • 2,120
  • 15
  • 27
0
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();
    }
}
Yen
  • 51
  • 3
0

looks like you are breaking you zip file during saving:

instead of:

outStream.write(data, 0, bytesRead);

try:

outStream.write(data);
injecteer
  • 20,038
  • 4
  • 45
  • 89