[英]How to download a file in Android
What i have: 我有的:
What i am trying to do: 我正在尝试做的是:
I want to download the file to my RAW folder
of my android project 我想将文件下载到我的android项目的
RAW folder
中
I am familiar with AsyncTask
and HttpClient
but what methodology(steps) should I follow to download the file? 我熟悉
AsyncTask
和HttpClient
但是应该遵循什么方法(步骤)来下载文件?
I tried searching for a similar question in stackoverflow but couldn't find one so posting a question myself 我尝试在stackoverflow中搜索类似的问题,但找不到一个问题,所以自己发布了一个问题
You cannot download a file into "assets" or "/res/raw". 您无法将文件下载到“资产”或“ / res / raw”中。 Those get compiled into your APK.
这些被编译到您的APK中。
You can download the file to your apps internal data directories. 您可以将文件下载到应用程序的内部数据目录。 See Saving Files |
请参阅保存文件| Android Developers .
Android开发人员 。
There are plenty of examples and libraries to help you with the download. 有许多示例和库可以帮助您进行下载。 The following is a static factory method you could use in your project:
以下是您可以在项目中使用的静态工厂方法:
public static void download(String url, File file) throws MalformedURLException, IOException {
URLConnection ucon = new URL(url).openConnection();
HttpURLConnection httpConnection = (HttpURLConnection) ucon;
int responseCode = httpConnection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
BufferedInputStream bis = new BufferedInputStream(ucon.getInputStream());
ByteArrayBuffer baf = new ByteArrayBuffer(50);
int current = 0;
while ((current = bis.read()) != -1) {
baf.append((byte) current);
}
FileOutputStream fos = new FileOutputStream(file);
fos.write(baf.toByteArray());
fos.close();
bis.close();
}
}
Then, to download a file from Dropbox: 然后,要从Dropbox下载文件:
String url = "https://dl.dropboxusercontent.com/u/27262221/test.txt";
File file = new File(getFilesDir(), "test.txt");
try {
download(url, file);
} catch (MalformedURLException e) {
// TODO handle error
} catch (IOException e) {
// TODO handle error
}
Please note that the above code should be run from a background thread or you will get a NetworkOnMainThreadException
. 请注意,以上代码应从后台线程运行,否则您将获得
NetworkOnMainThreadException
。
You will also need to declare the following permission in your AndroidManifest: 您还需要在AndroidManifest中声明以下权限:
<uses-permission android:name="android.permission.INTERNET" />
You can find some helpful libraries here: https://android-arsenal.com/free 您可以在这里找到一些有用的库: https : //android-arsenal.com/free
I personally recommend http-request . 我个人建议使用http-request 。 You could download your dropbox file with HttpRequest like this:
您可以使用HttpRequest下载您的保管箱文件,如下所示:
HttpRequest.get("https://dl.dropboxusercontent.com/u/27262221/test.txt").receive(
new File(getFilesDir(), "test.txt"));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.