我嘗試下載一個zip文件到android,然後解壓zip文件。我調試我的代碼,並有一個有趣的問題:下載的zip文件比原始文件大一點。並且下載的zip文件不能被winrar解壓縮。據說下載的文件以錯誤結束。 (。上我的網站的zip文件是好的,我嘗試用IE下載它工作正常) 以下是我的代碼:如何在android中正確地下載帶有java代碼的zip文件?
public void download(final String url, final String savePath, final String saveName) {
new Thread(new Runnable() {
public void run() {
try {
sendMessage(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);
if (readNum > -1) {
outputStream.write(buffer);
readCount = readCount + readNum;
int percent = (int) (readCount * 100/fileSize);
if (percent > prevPercent) {
sendMessage(FILE_DOWNLOAD_UPDATE, percent,
readCount);
prevPercent = percent;
}
}
}
outputStream.flush();
outputStream.close();
inputStream.close();
//Thread.sleep(50);
sendMessage(FILE_DOWNLOAD_COMPLETE, savePath);
} catch (Exception e) {
sendMessage(FILE_DOWNLOAD_ERROR, e);
}
}
}).start();
}
有人知道這個問題?
我曾嘗試之前討論的解決方案:[鏈接](http://stackoverflow.com/questions/9324103/download-and-extract-zip-file-in-android)。但同樣的問題在那裏。 – David 2012-04-11 05:23:44
另一個有趣的問題。下載後的文件大小會在我再次下載後發生變化(不是每次都是這樣)我想這可能是由android文件緩衝策略造成的。所以我嘗試//Thread.sleep(50);讓android完全保存文件。但它似乎不起作用。 (zip文件需要在下載後立即提取。) – David 2012-04-11 05:27:51