繁体   English   中英

如何在Android中下载文件

[英]How to download a file in Android

我有的:

  1. 我已将.json文件上传到我的帐户的Dropbox中,并将其公开

我正在尝试做的是:

  1. 我想将文件下载到我的android项目的RAW folder

  2. 我熟悉AsyncTaskHttpClient但是应该遵循什么方法(步骤)来下载文件?

我尝试在stackoverflow中搜索类似的问题,但找不到一个问题,所以自己发布了一个问题

您无法将文件下载到“资产”或“ / res / raw”中。 这些被编译到您的APK中。

您可以将文件下载到应用程序的内部数据目录。 请参阅保存文件| Android开发人员

有许多示例和库可以帮助您进行下载。 以下是您可以在项目中使用的静态工厂方法:

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();
    }
}

然后,要从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
}

请注意,以上代码应从后台线程运行,否则您将获得NetworkOnMainThreadException

您还需要在AndroidManifest中声明以下权限:

<uses-permission android:name="android.permission.INTERNET" />

您可以在这里找到一些有用的库: https : //android-arsenal.com/free

我个人建议使用http-request 您可以使用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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM