Android - 正确地将res / raw资源复制到SD

时间:2012-08-05 14:24:45

标签: android copy inputstream outputstream

好吧,我尝试了很多东西,但是我实现的更好的目标是将所需的文件复制到sd,但新的文件大小总是为0bytes :(

这是我的代码:

        String baseDir = Environment.getExternalStorageDirectory().getAbsolutePath();
        String fileName = sonidoActual+".mp3";

        File newSoundFile = new File(baseDir, fileName);
        Uri mUri = Uri.parse("android.resource://com.genaut.ringtonelists/raw/"+sonidoActual);
        AssetFileDescriptor soundFile;
        try {
            soundFile= getContentResolver().openAssetFileDescriptor(mUri, "r");
        } catch (FileNotFoundException e) {
            soundFile=null;   
        }

        try {
            byte[] readData = new byte[1024*500];
            FileInputStream fis = soundFile.createInputStream();
            FileOutputStream fos = new FileOutputStream(newSoundFile);
            int i = fis.read(readData);
            while (i != -1) {
                fos.write(readData, 0, i);
                i = fis.read(readData);
                Log.d("Degug - While: ", "i: "+i);
            }
            fos.flush();
            fos.close();
        } catch (IOException io) {
        }

抱歉我的英语不好。有人知道这个问题吗?非常感谢!

我的清单上有这些权限:

<uses-permission android:name="android.permission.WRITE_SETTINGS" />
<uses-permission android:name="android.permission.CHANGE_CONFIGURATION" />
<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

更多信息: 我尝试了一些代码来复制assets中的文件而无法正常工作..我有一些应用程序可以很好地设置铃声,所以我不认为我的SD有问题..我感到绝望:S

这些是来自资产的代码,显然效果很好:https://stackoverflow.com/a/4530294/1422434


我也试过getResources.openRawResource():,但没有效果

    String baseDir = Environment.getExternalStorageDirectory().getAbsolutePath();
String fileName = nombreActual+".mp3";

File newSoundFile = new File(baseDir, fileName);

try {
    byte[] readData = new byte[1024*500];
    InputStream fis = getResources().openRawResource(contexto.getResources().getIdentifier(sonidoActual,"raw", contexto.getPackageName()));
    FileOutputStream fos = new FileOutputStream(newSoundFile);
    int i = fis.read(readData);

    while (i != -1) {
        fos.write(readData, 0, i);
        i = fis.read(readData);
    }

    fos.close();
} catch (IOException io) {
}

1 个答案:

答案 0 :(得分:2)

当您使用原始文件夹时,只需在您的活动中使用此文件:

getResources().openRawResource(resourceName)