我尝试将 zip 文件下载到 android,然后提取 zip 文件。我调试了我的代码,有一个有趣的问题:下载的 zip 文件比原始文件大一点。而且下载的zip文件不能被winrar解压。据说下载的文件以错误结束。(我网站上的 zip 文件没问题。我尝试用 IE 下载。它工作正常。)以下是我的代码:
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();
}
有人知道这个问题吗?