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?