【问题标题】:Download(copy?) a file from my res/raw folder to the default Android download location?将我的 res/raw 文件夹中的文件下载(复制?)到默认的 Android 下载位置?
【发布时间】:2015-03-03 03:45:42
【问题描述】:

我正在制作一个用于练习的音板,我想让用户能够在单击菜单项时下载声音(我已包含在应用程序的 res/raw 文件夹中),但我只能找到有关从互联网网址下载,而不是我已经包含在 apk 中的内容。

最好的方法是什么?如果可能的话,我也想给他们保存到 SD 卡的选项。在文档中使用正确的类会很棒!我一直在谷歌搜索无济于事。

谢谢!

【问题讨论】:

  • 这个挺简单的,现在写一个答案……
  • 谷歌搜索copy file from res/raw to sdcard。

标签: android


【解决方案1】:

试试这样的:

public void saveResourceToFile() {
InputStream in = null;
FileOutputStream fout = null;
try {
    in = getResources().openRawResource(R.raw.test);
    String downloadsDirectoryPath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getAbsolutePath();
    String filename = "myfile.mp3"
    fout = new FileOutputStream(new File(downloadsDirectoryPath + filename));

    final byte data[] = new byte[1024];
    int count;
    while ((count = in.read(data, 0, 1024)) != -1) {
        fout.write(data, 0, count);
    }
} finally {
    if (in != null) {
        in.close();
    }
    if (fout != null) {
        fout.close();
    }
}
}

【讨论】:

  • 这看起来就是我需要的——如果手机上没有sd卡,会下载到默认的下载文件夹吗?还是 getExternalStorageDirectory() 只是找到他们在手机上设置的任何存储区域?谢谢!
  • 是的,它将“下载”到下载文件夹(可能会有所不同),但这只是一个基本示例,您可能需要检查 SD 卡是否可写等。顺便说一句,那里是android开发者网站here上的完整代码示例,可能比这个更好。
【解决方案2】:

我不知道raw,但我在我的应用程序中使用assets 文件夹做了类似的事情。我的文件位于assets/backgrounds 文件夹下,您可以从下面的代码中猜到。

您可以修改此代码并使其适合您(我知道我将只有 4 个文件,这就是为什么我将 i 从 0 变为 4 但您可以将其更改为任何您想要的)。

此代码会将以prefix_ 开头的文件(如 prefix_1.png、prefix_2.png 等)复制到我的缓存目录,但您显然可以更改扩展名、文件名或要将资产保存到的路径.

public static void copyAssets(final Context context, final String prefix) {
    for (Integer i = 0; i < 4; i++) {
        String filename = prefix + "_" + i.toString() + ".png";
        File f = new File(context.getCacheDir() + "/" + filename);
        if (f.exists()) {
            f.delete();
        }

        if (!f.exists())
            try {
                InputStream is = context.getAssets().open("backgrounds/" + filename);
                int size = is.available();
                byte[] buffer = new byte[size];
                is.read(buffer);
                is.close();

                FileOutputStream fos = new FileOutputStream(f);
                fos.write(buffer);
                fos.close();
            } catch (Exception e) {
                Log.e("Exception occurred while trying to load file from assets.", e.getMessage());
            }
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-09-07
    • 1970-01-01
    • 2021-05-28
    • 1970-01-01
    • 2012-06-20
    • 1970-01-01
    • 2020-04-24
    相关资源
    最近更新 更多