从我的res/raw文件夹下载(复制?)一个文件到默认的Android下载位置



我正在制作一个用于练习的声卡,我想让用户能够下载声音(我已经在res/raw文件夹中的应用程序中包含了声音)。点击菜单项,但我只能从互联网url找到下载信息,而不能找到我已经包含在apk中的信息。

最好的方法是什么?如果可能的话,我想给他们保存到SD卡的选项。如果能在文档中使用正确的类,那就太好了!我一直在谷歌上搜索,但没有结果。

谢谢!

试试这样的东西:

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

我不知道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());
            }
    }
}

最新更新