如何在Android中以编程方式从net下载文件? [英] How to download files from net programmatically in Android?
本文介绍了如何在Android中以编程方式从net下载文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在我的应用程序中,从Web下载文件的负载约为200Mb文件(压缩)。如何在Android中以编程方式下载文件?实际上,我关心的是代码的性能。我该如何处理介于两者之间的错误和网络问题?
In my application downloading loads of files from web they were around 200Mb files(Zipped). How do I download files programmatically in Android? Actually my concern is about performance of code. How do I handle errors and network problem in between?
推荐答案
以下是我最近为此编写的一些代码:
Here's some code that I recently wrote just for that:
try {
URL u = new URL("http://your.url/file.zip");
InputStream is = u.openStream();
DataInputStream dis = new DataInputStream(is);
byte[] buffer = new byte[1024];
int length;
FileOutputStream fos = new FileOutputStream(new File(Environment.getExternalStorageDirectory() + "/" + "file.zip"));
while ((length = dis.read(buffer))>0) {
fos.write(buffer, 0, length);
}
} catch (MalformedURLException mue) {
Log.e("SYNC getUpdate", "malformed url error", mue);
} catch (IOException ioe) {
Log.e("SYNC getUpdate", "io error", ioe);
} catch (SecurityException se) {
Log.e("SYNC getUpdate", "security error", se);
}
这将下载文件并将其放在您的sdcard中。
This downloads the file and puts it on your sdcard.
您可能可以修改此设置以满足您的需求。 :)
You could probably modify this to suit your needs. :)
这篇关于如何在Android中以编程方式从net下载文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文