我使用此代码从链接下载到sdcard
此代码在模拟器中完全运行但在移动设备中无效
在创建的移动文件中,但文件容量为零且未下载完整
如何修复它?!
注意:我理解我的代码不适用于4版本,有什么问题?!
THX
public class FileDownloader {
public static void download(final String downloadPath, final String filepath, final OnProgressDownloadListener listener) {
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
try {
URL url = new URL(downloadPath);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setDoOutput(true);
connection.connect();
int fileSize = connection.getContentLength();
File file = new File(filepath);
if (file.exists()) {
file.delete();
}
FileOutputStream outputStream = new FileOutputStream(filepath);
InputStream inputStream = connection.getInputStream();
byte[] buffer = new byte[G.DOWNLOAD_BUFFER_SIZE];
int len = 0;
int downloadedSize = 0;
while ((len = inputStream.read(buffer)) > 0) {
outputStream.write(buffer, 0, len);
downloadedSize += len;
final float downloadPercent = 100.0f * (float) downloadedSize / fileSize;
Log.i("PER", "" + downloadPercent);
if (listener != null) {
G.HANDLER.post(new Runnable() {
@Override
public void run() {
listener.onProgressDownload((int) downloadPercent);
}
});
}
}
outputStream.close();
}
catch (MalformedURLException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
}
});
thread.start();
}
}
答案 0 :(得分:0)
我删除了这一行并完成了工作:
connection.setDoOutput(true);