如何下载 Android 中的文件

How to download a file in Android

我有:

  1. 我已将 .json 文件上传到我帐户的 Dropbox 做到了 public

我想做什么:

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

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

我尝试在 Whosebug 中搜索类似的问题,但找不到,所以自己发帖提问

您不能将文件下载到 "assets" 或“/res/raw”。这些会被编译到您的 APK 中。

您可以将文件下载到您的应用内部数据目录。参见 Saving Files | Android Developers

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

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"));